The catchError operator

Like catchErrorJustReturn, it will catch and switch to another observable. The difference is that the recovery observable does not need to immediately emit and terminate. It can continue emitting. Let's start by creating the PublishSubject, and we will also create a recovery sequence as follows:

example(for: "catchError") {
let disposeBag = DisposeBag()
let pubSubject = PublishSubject<String>()

let recoverySeq = PublishSubject<String>()
}

We will use the catchError operator on the subject to print out the error and then return the recovery sequence, as shown:

let disposeBag = DisposeBag()
let pubSubject = PublishSubject<String>()

let recoverySeq = PublishSubject<String>()

pubSubject.catchError({
print("Error=", $0)
return recoverySeq
})

Now we will subscribe and print events, as illustrated:

pubSubject.catchError{
print("Error=", $0)
return recoverySeq
}
.subscribe { print($0) }
.disposed(by: disposeBag)

First, we will add a value to this subject, and then we will add an error, as we did in the previous example:

pubSubject.catchError{
print("Error=", $0)
return recoverySeq
}
.subscribe { print($0) }
.disposed(by: disposeBag)

pubSubject.onNext("First element")
pubSubject.onError(CustomError.test)

Note that the completed event has not emitted in the console logs:

Let's add another value to the subject, as follows:

pubSubject.onNext("First element")
pubSubject.onError(CustomError.test)
pubSubject.onNext("Second element")

Now, you will note that the value is not emitted, as depicted here:

This is because the subject terminated with an error event, but the subscription switched to the recover sequence. So let's add a value to the recovery, as follows:

pubSubject.onNext("First element")
pubSubject.onError(CustomError.test)
pubSubject.onNext("Second element")

recoverySeq.onNext("Third element")

You will note that this event is emitted by the recovery sequence, as shown:

Next, we will discuss the retry operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset