Search code examples
reactive-programmingrx-java2project-reactor

Reactive streams with reactive side-effects


I think this will be done similarly with most reactive implementations so I do not specify any specific library&language here.

What is the proper way to do reactive side effects on streams (not sure what is the proper terminology here)?

So lets say we have a stream of Players. We want to transform that to a stream of only ids. But in addition to that, we want to do some additional reactive processing based on the ids.

Here is how one can do in not so elegant way, but what is the idiomatic way to achieve this:

Observable<Player> playerStream = getPlayerStream();
return playerStream
      .map(p -> p.id)
      .flatmap(id -> {
           Observable<Result> weDontCare = process(id);
           // Now the hacky part
           return weDontCare.map(__ -> id);
      })

Is that ok? Seems not so elegant.


Solution

  • Observable<Player> playerStream = getPlayerStream();
        return playerStream
              .map(p -> p.id)
              .doOnEach(id -> { //side effect with id
                Observable<Result> weDontCare = process(id);
                weDontCare.map(__ -> id);
              })