Sebastian
Sebastian

Reputation: 1732

RxJava get result of previous observable in chained network request

I have 2 service endpoints in my application a and b (Both are "Singles"). The request to service b depends on the response of a. After the the response of b I need access to both responses in my subscriber. I plan to do the call like this:

services.a()
    .flatMap(a -> services.b(a))
    .subscribe(b ->
        // Access a and b here
    )

But in this way, I only can access the result of b in my subscriber. How can I pass also the response of a to it?

My first attempt was to use something like this:

// Note: Code will not compile... Just to show the concept
services.a()
    .flatMap(
        a -> Observable.combineLatest(
                Observable.just(a)
                services.b(a).toObservable()
                Bifunction((a, b) -> {return Pair<ResponseA, ResponseB>(a, b)}))
    )
    .toSingle()
    .subscribe(pair -> {
        ResponseA a = pair.first();
        ResponseB b = pair.second();
    })

But as the use case gets a bit more complex, the code will evolve to an ugly monster.

Upvotes: 6

Views: 2972

Answers (1)

yosriz
yosriz

Reputation: 10267

You can use a variant of flatMap() with resultSelector, resultSelector method will gather both input (a) and output (result of Observable b) of the flatMap and you can combine them together to whatever you need. See here.

Upvotes: 4

Related Questions