Reputation: 2275
I have 3 API requests which i am handling with RxJava Chaining (Using FlatMap).
For Example : A , B , C
Request A is giving HttCode Error 400. So i want data of its response body to show error message in UI. I handled it in onError() method & parse body data. But don't know how to send it to Observer without stoping chain. If i am using . Observer.just(ErrorData). It is throwing it into next Request B FlatMap.
Request B & C are dependent on each other. Request B execute after A. I don't want to stop their execution if there is error in Request A.
So i need Request A Error data & Request C Success data in Observer to show Error message & Success data respectively.
Can anybody suggest any idea to solve it ?
Upvotes: 0
Views: 220
Reputation: 1093
You can achieve this by Mapping Observable types to monad type. ie, Map the Observables to a type that can hold both error and success states, if an error is thrown in observable stream A, error type is propogated using onErrorResumeNext.
Map observables B and C such that it can hold the error message from A. while flat mapping A with B, check the type of the value emitted from A and if the value is error type propogate the error message into C as well
Here is an example I tried in kotlin
val obs1 = Observable.create<Float> {
throw IllegalStateException("Shit happens")
}
val obs2 = Observable.just(1)
val obs3 = Observable.just("hii")
obs1.map { Result(null, it) }.onErrorResumeNext { er: Throwable ->
Observable.just(Result<Float>(er.message, null))
}.flatMap { fltResult ->
obs2.map { Result(fltResult.error, it) }
}.flatMap { intResult ->
obs3.map { Result(intResult.error, it) }
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe({
Log.d("Data: Error", it.data + ": " + it.error)
}, {
Log.d("Error", it.message)
})
Result class being
data class Result<T>(val error : String?,val data : T?)
Upvotes: 1