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.
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
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.
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
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With