Search code examples
javaproject-reactorreactive-streams

How to call both subscribe and blockLast on Flux?


I have been experimenting with Project Reactor and reactive streams in general. I encountered an issue when using subscribeOn to make stream run on a different thread. Having my code in a main, I need main thread block until the stream finishes, so I did something like this:

        Flux.just(1, 2, 3, 4)
                .log()
                .subscribeOn(Schedulers.parallel())
                .subscribe((i) -> {
                   // some operation 
                });

        try {
            Thread.sleep(20000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Finished");

Then I noticed that there is a blockLast() methods that does the blocking. But I couldn't use both subscribe and blockLast since they don't return Flux.

Is there a graceful way to do this?


Solution

  • All the block methods do the subscribe on your behalf. You can move code that you would have put in subscribe lambdas into the equivalent doOn* methods