javaspringreactorreactive-streams

What is the best way to do async side effect in Reactor?


Let's assume I have a main chain with some processing and I want to call billing service on each item processed and then return the results of the processing further like so:

... ... ... // chain starts somewhere here
.flatMap(item -> processItem(item))
.doOnNext(item -> billingService.bill(item))
... ... ... // continue to work with processed items

i.e I want to do some side effect action on the chain. This would work if billingService.bill() were sync, but it returns Mono. So, here's what I have to do instead:

... ... ... // chain starts somewhere here
.flatMap(item -> processItem(item))
.flatMap(item -> billingService.bill(item).thenReturn(item))
... ... ... // continue to work with processed items

Is there a better way to do it? Seems kinda awkward to me...


Solution

  • This fire and forget pattern answers my question. So in my case it will look like this:

    ... ... ... // chain starts somewhere here
    .flatMap(item -> processItem(item))
    .doOnNext(item -> billingService.bill(item).subscribe())
    ... ... ... // continue to work with processed items