RxSwift icon indicating copy to clipboard operation
RxSwift copied to clipboard

How to chain Observables and create one common place for error handling?

Open robertherdzik opened this issue 10 years ago • 5 comments

I'm wondering how to write my code in more elegant way... I was asked the similar question on stackoverflow but there was no any response. Let say that I have two requests, the second request have to wait for the first one. If the first one gets failed the whole sentence should failed, I'm wondering how to catch error in one common place for both requests?

`enum TestError: ErrorType { case Connection }

private func runTest() {
    rx_firstReq()
        .subscribeNext() { _ in
            return self.rx_secondReq()
                .subscribeNext() { _ in
                    print("whole req sequence finished with success!")
            }.addDisposableTo(self.myDisposeBag)
    }.addDisposableTo(myDisposeBag)
}

func rx_firstReq() -> Observable<Bool> {
    return Observable.create() { observable -> Disposable in
        observable.onError(TestError.Connection) // We are assuming that first req gets failed
        observable.onCompleted()

        return NopDisposable.instance
    }
}

func rx_secondReq() -> Observable<Bool> {
    return Observable.create() { observable -> Disposable in
        observable.onNext(true)
        observable.onCompleted()

        return NopDisposable.instance
    }
}`

As you see there is no any place for error handling... I have no idea how to model it, at this moment each next request in my chain gonna create next indentation level... in my opinion it is not good usage of the RxSwift... 😕

..some hint or link with example code with handling error in common place will be great for me.

robertherdzik avatar Apr 05 '16 19:04 robertherdzik

Hi @robertherdzik ,

please don't use RxSwift this way, or you will hate it for sure :)

We've tried to explain that in Tips.md

There is a bunch of practical code samples in RxExample app inside this repro. I suggest taking a look at them and reading GettingStarted.md

When using operators, operators will propagate errors for you.

kzaher avatar Apr 05 '16 20:04 kzaher

Try flatmap and flatmaplatest.

taonos avatar Apr 05 '16 20:04 taonos

I've chained dependent network calls before like this. Basically, use firstReq().flatMap { return secReq() } to subscribe to the second request once the first is finished. If an error occurs in either the first or the second, you can subscribe to the error in the same place.

ashfurrow avatar Apr 05 '16 20:04 ashfurrow

Ok guys, now I catch the idea :) Thanks a lot!

robertherdzik avatar Apr 06 '16 16:04 robertherdzik

Is there a better way to do this type of chaining up requests? It just seems like all you're doing is nesting instead of chaining ....

Say I would like to have request1 run before request2.... Would you suggest use Observable.zip over flatmap?

rlam3 avatar Dec 03 '16 06:12 rlam3