Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Reactor: fire and forget Action on doOnNext

I have a Flux stream. For each elements processed I want to have an action triggered which is an asynchronous/non-blocking one. For example a method returning back a mono from a db update.
I want this action to be done on the doOnNext block.
I don’t want to affect the Flux, the processing and the back pressure implemented there.

Supposing mono method to be called is

Mono<Integer> dbUpdate();

should my Flux be like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public Flux<Data> processData(PollRequest request)
{
    return searchService.search(request)              
                        .doOnNext(data -> dbUpdate(data));
}

Or should be as mentioned on a stack overflow example.

public Flux<Data> processData(PollRequest request)
{
    return searchService.search(request)              
                        .doOnNext(data -> dbUpdate(data).subscribe());
}

Won’t the above cause blocking issues inside doOnNext?

Also which is the most appropriate scheduler to use for this type of action?

>Solution :

dbUpdate() will be ignored if you do not subscribe to it. The following snippet doesn’t print anything because Mono.just("db update") doesn’t get subscribed.

Mono<String> dbUpdate() {
    return Mono.just("db update")
        .doOnNext(System.out::println);
}

public Flux<String> processData() {
    return Flux.just("item 1", "item 2")
        .doOnNext(data -> dbUpdate());
}

Note that .subscribe() doesn’t block your thread, it kicks off the work and returns immediately.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading