Search code examples
javafluxreactorspring-reactive

Reactor: Flux<object> .subscribe() vs. .toStream()


I have a function: Flux queryPerson() which queries database to generate the objects and return them in Flux. When I use .subscribe(), the app just run thru the code and exit. It doesn't wait for the results to come back for the query. But when I use .toStream() to block the stream, I can see the printouts. What am I doing wrong?

personRepository
    .queryPerson()
    .map(x -> x.getFirst().concat("ok"))
    .subscribe(i -> System.out.println(i))
    //.toStream().forEach(System.out::println)
;

Solution

  • I'd assume you do not have some kind of web app but rather a command line runner or simple java app. Considering that it is normal for application to finish before asynchronous tasks.

    .subscribe

    Subscription is an asynchronous way of consuming incoming data, after you subscribe on Flux you immediately return control to the calling thread.

    This is exactly how reactive programming works, you define behavior, you have nice abstract way of running it in some other threads and with your calling thread.

    as it states in Flux docs

    since the sequence can be asynchronous, this will immediately return control to the calling thread. This can give the impression the consumer is not invoked when executing in a main thread or a unit test for instance.

    .toStream

    On the other hand with .toStream you receive a Java Stream, and even tho it is of unknown size, you still iterate it in synchronous way like a normal Java Stream.

    More explanation can be found in .toStream docs of Flux