RxSwit - driver from observable ignoring errors

3.5k views Asked by At

Let's say I have some view initally filled with some data. Than I fetch data over network and want to update view with this updated data.

At this point I want to create Driver from this observable to drive UI elements. However in case of error in observable I don't want to do anything, as the view has already some data so I just want to ignore such error. asDriver() function wants to define what should be done in case of error. Is it ok to do it like this:

let dataUpdated: Observable<DataItem> = ...

let driver = dataUpdated.asDriver(onErrorDriveWith: Driver<DataItem>.empty())

?

3

There are 3 answers

3
CZ54 On

Why are you not using catchErrorJustReturn(DataItem()) ?

0
André Schmidt On

As suggested the solution could be to use .filter(). I imagine something like this will solve your problem:

extension Observable {
    func asDriverIgnoringErrors() -> Driver<E> {
        return self.map { $0 as E? }
            .asDriver(onErrorJustReturn: nil)
            .filterNil()
    }
}
0
dollar2048 On

Try this:

extension ObservableType {
    public var asDriverSkippingErrors: Driver<Element> {
        return map { Optional($0) }
            .asDriver(onErrorJustReturn: nil)
            .unwrap()
    }
}