Search code examples
androidrx-java2

Chaining N dependant observables


I'm quite new to reactive programming and I've introduced myself to RxJava2 in Android. For the time being, I've faced easy problems, such as zipping observables. But now, something new cropped up, I'm trying to explain.

Suppose I've got a list of requests Observable<List<Request>>. What I want to do is to call a web service which returns per each request, the list of routes (wrapped in an Observable). I've checked questions like this, but in this case I think I can't flatMap an observable and a list of observables.

How can I do it? Is there any other operator?


Solution

  • You can flatten the Observable<List<Request>> into Observable<Request> using flatMapIterable. Assuming you have a helper method with the signature Observable<List<Route>> getListOfRoutes(Request request) { ... } you can do this:

    Observable<List<Request>> obs = ...;
    obs.flatMapIterable(l -> l)
       .flatMap(request -> getListOfRoutes(request)
           .doOnNext(routes -> request.setRoutes(routes))
           .map(ign -> request)
       )
       ...
    

    This is assuming that you ultimately want Observable<Request> to be emitted downstream. If you want a different type, you can do something different in the map operator to suit your needs.