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.
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.
Try flatmap and flatmaplatest.
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.
Ok guys, now I catch the idea :)
Thanks a lot!
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?
Most helpful comment
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.