Reputation: 31
i could not understand why this simple code is not working. I m trying to save the initial value of my reactor Mono and reuse it later.
Mono.just("titi caca")
.flatMap(m -> Mono.just(m).contextWrite(context -> context.put("INITIAL", m)))
.log()
.flatMap(m -> Mono.just(m.toUpperCase()))
.log()
.flatMap(m -> Mono.<String>deferContextual(contextView -> contextView.get("INITIAL")))
.log()
.subscribe();
it ends with "Context does not contain key: INITIAL" ? did i completly misunderstanding this feature ?
Upvotes: 2
Views: 9421
Reputation: 1
I have an example to demonstrate how to use .contextWrite(), which can run in my project
return dispatchService.requestHandWritingOcr(batchRequest)
// get ctx
.transformDeferredContextual((req, ctx) ->{
System.out.println(ctx.get(Const.APPID).toString());
System.out.println(ctx.get(Const.TRACE_ID).toString());
return req;
})
// doSomething
.map(OpenResponse::success)
// write context on last
.contextWrite(ctx -> {
// context can not change, like String
// if you put something in ctx, it will return new ctx
// if you want it work, you need get and return new ctx
if (StrUtil.isNotBlank(appId)) {
ctx = ctx.put(Const.APPID, appId);
}
if (StrUtil.isNotBlank(traceId)) {
ctx = ctx.put(Const.TRACE_ID, traceId);
}
return ctx;
});
Upvotes: 0
Reputation: 161
First of - deferContextual()
should be before contextWrite()
in the code lines, as mentioned by @amanin.
Second - contextWrite()
in flatMap()
impact on Mono only in nested line.
If you want to pass argument to downstream, you can create object in Mono.fromCallable()
or Mono.fromSupplier()
or others and use it there.
See: https://projectreactor.io/docs/core/release/reference/
Upvotes: 1
Reputation: 123
Same thing happened for me when i was adding value to context in this way, but it worked when added like below :
contextWrite(Context.of("INITIAL","value") --- Working fine
contextWrite(ctx -> ctx.put("INITIAL","value")) --- Not working correctly
Upvotes: 1