Issue
I'm starting with Project Reactor and I cant understand why is this code infinitely prints "Hello" and never returns the Disposable
object.
Flux<Object> flux = Flux.generate(sink -> sink.next("Hello"));
Disposable disposable = flux.subscribe(System.out::println);
disposable.dispose();
System.out.println("This doesn't print");
I thought that when it comes to call subscribe()
method it must immediately return the Disposable
object with which I can unsubscribe if I want. I know that code inside this subscribe
method running in the same thread and if I substitute the delayElements
method before the subscribe
call then the code below will work because it runs in a separate daemon thread, so can any explain why does it stop at the subscribe
method and not return Disposable
and are there any ways to manage a subscription by calling the subscribe
method? Is it possible to make it so that, by analogy with the delayElements
method, this is executed in a separate thread and the result of calling the subscribe
method returns Disposable
immediately?
I couldn't find an answer specifically to this question. In all the examples that I saw there was either a finite data stream or the delayElements method was used.
Solution
Yes, subscribe()
is blocking in this particular scenario.
Reactor is concurrency agnostic which means by default it doesn't enforce any threading/asynchronicity on you and executes the pipeline on the calling thread (in this particular case the main thread).
You can change this explicitly by using subscribeOn
or publishOn
, or implicitly by using some operators like delayElements
.
Flux<Object> flux = Flux.generate(sink -> sink.next("Hello")).publishOn(Schedulers.parallel());
Disposable disposable = flux.subscribe(System.out::println);
disposable.dispose();
System.out.println("This doesn't print");
Answered By - Martin Tarjányi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.