onErrorRecover

At times, we might want to perform an additional action before recovering from an error like this; for this, we have onErrorRecover. It schedules a recovery sequence to run on the next loop. In order to show this on playground, we need to write this on a global scope, that is, not enclose it in the example (for) method call, and we will also need to import playground support and set needsIndefiniteExecution to true. This will give schedule recovery time to execute. We will write something like this:

print("... Example for: Driver onErrorRecover.....")
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

We will now duplicate the code from within the first example again, and this time, we will use onErrorRecover, which can be written as trailing closure on asDriver. We will print the error, and then we will return the single element sequence for simplicity sake, but this could have been a Driver, like we used in the previous example, that would keep on driving. The code will look as follows:

print("... Example for: Driver onErrorRecover.....")
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let disposeBag = DisposeBag()
let pubSubject = PublishSubject<Int>()
pubSubject.asDriver{
print( "Error:", $0 )
return Driver.just(1000)
}
.drive(onNext: {
print ( $0 )
})
.disposed(by: disposeBag)
pubSubject.onNext(10)
pubSubject.onNext(20)
pubSubject.onError(CustomError.test)

In the console, you will note that the first two elements are printed, then the error, and then the recover Driver, as shown:

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

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