1

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)
;
JavaMan
  • 1,142
  • 12
  • 22
topcan5
  • 1,511
  • 8
  • 30
  • 54

1 Answers1

3

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

Emil Hotkowski
  • 2,233
  • 1
  • 13
  • 19
  • Thanks for the answer. You are right. I am just running a normal java app in the console. Is that mean I can only use toStream() in the none-web application? – topcan5 Nov 25 '19 at 20:38
  • The whole idea behind subscribe is to not block your main thread to wait for answer. For example let say that in web app you make some heavy database query and then return to client with answer, non blocking/ reactive code is way to go BUT since you have one main thread and it ends (program ends) before it prints you just don't see them. If you had longer running program, you would see those prints, I don't know your case if it is a real app or training one, just use toStream and iterate it to see the results. – Emil Hotkowski Nov 25 '19 at 20:41
  • There is a great and popular text about Reactive Programming on the internet, I highly recommend to read at least first part of it https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 – Emil Hotkowski Nov 25 '19 at 20:44
  • 1
    @topcan5 It's not so much you need a Web application but that you need a more complex application to really see the benefits of reactive programming. Basically, you need a longer-lived application where it makes sense to offload work to the background. An example is obviously a Web application; another is a desktop GUI application. – Slaw Nov 25 '19 at 21:35