Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 993
Sebastian Avatar asked Jun 19 '17 06:06

Sebastian


People also ask

What are the components of RxJava?

RxJava basically has three types of components. They are: They are defined as follows: Observable emits some values. Operator operates (modifies) the emitted value by Observable Observer receives those values emitted by Observable and modified by Operator

What is the difference between single and maybe in RxJava?

Single is used when the Observable has to emit only one value like a response from network call. This is the most common Observable we will be using in RxJava as most of our applications involve Network Calls. Maybe is used when the observable has to emit a value or no value.

When to use maybe in RxJava for Android application development?

This is the most common Observable we will be using in RxJava as most of our applications involve Network Calls. Maybe is used when the observable has to emit a value or no value. It is not recommended much to use Maybe in RxJava for Android Application Development

How to prevent overflooding in RxJava?

In the previous version of RxJava, this overflooding could be prevented by applying back pressure. But in RxJava 2, the development team has separated these two kinds of producers into two entities. i.e. Observable and Flowable. According to documentation:


1 Answers

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.

like image 128
yosriz Avatar answered Oct 04 '22 01:10

yosriz