I have a class PublishContext with a method context() as follows :
public static Mono<Object> context(){ return Mono.empty().subscriberContext( context -> { Context context1 = context.put("key", "hello"); System.out.println((String) context1.get("key")); return context1; }); }
In above code, context object is Context0@744 and context1 is Context@747 which is understandable since context is immutable and always returns a new context.
In my main class, I have the following code :
public static void main(String[] args) { Mono<Object> objectMono = PublishContext.context(); objectMono.subscribe(); Mono<Object> objectMono1 = Mono.subscriberContext().flatMap(context -> { System.out.println((String) context.get("key")); return Mono.empty(); }); objectMono1.subscribe(); }
Here, I am getting context as Context0@744, i.e Old context and hence, getting “context is empty” exception. Can someone please explain this behaviour? Also, How can I access context0@747 which I am returning from my context() method?
Advertisement
Answer
- A) the
Context
write needs to be part of the same chain of operators - B) it needs to be “downstream” of the part where you need to read it
As such, a “self-contained” sequence where you have the source (Mono.empty()
), the Context
write (.subscriberContext(...)
) AND the final step of subscribing (objectMono.subscribe()
) doesn’t make much sense.
Maybe try turning context()
into a decorating method?
public static <T> Mono<T> addContext(Mono<T> source){ return source.subscriberContext( context -> { Context context1 = context.put("key", "Hello"); System.out.println((String) context1.get("key")); return context1; }); }
Then apply and read it:
public static void main(String[] args) throws Exception { Mono<String> mono = Mono.just("foo") .flatMap(value -> Mono.subscriberContext() .map(ctx -> value + ctx.getOrDefault("key", "UNKNOWN")) ); Mono<String> monoWithCtxWrite = addContext(mono); mono.subscribe(System.out::println); monoWithCtxWrite.subscribe(System.out::println); }
This prints (provided the main doesn’t exit too early):
fooUNKNOWN fooHello