I'm trying to pass a parameter through the webClient context to understand how the reactive context works.
.post()
.uri(uri)
.headers(httpHeaders -> httpHeaders.putAll(headers))
.body(BodyInserters.fromObject(payload))
.exchange()
.flatMap( s -> Mono.subscriberContext()
.map( ctx -> {
System.out.println(“SubscriberContext1 " + ctx.getOrDefault("test", "DefaultValue”));
return s;
}))
.flatMap(resp -> {
return resp
.bodyToMono(Object.class)
.defaultIfEmpty(new HashMap<>())
.map(body -> {
//I would like to access the context variable here
return doSomething(body, contextVariable);
});})
.flatMap( s -> Mono.subscriberContext()
.map( ctx -> {
System.out.println("SubscriberContext2” + ctx.getOrDefault("test", "DefaultValue”));
return s;
}))
.subscriberContext(ctx -> {
System.out.println("WRITE TEST");
ctx.put("test", "test");
return ctx;
});
This prints out:
WRITE TEST
SubscriberContext1 DefaultValue
SubscriberContext2 DefaultValue
I'd expect it to be:
WRITE TEST
SubscriberContext1 test
SubscriberContext2 test
Why is the context variable not accessible within the flatMap?
ctx.put creates a new context. Changing the code to:
.subscriberContext(ctx -> {
System.out.println("WRITE TEST");
return ctx.put("test", "test");
});
solves it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.