简体   繁体   中英

Ignore error on Completable - RxSwift

Is there a way to ignore a completable if there is an error ? For example, I wan't to remove value in my Firebase Realtime Database , and delete a picture to Firebase Storage when the first completable has finish :

// MARK: DELETE - FUNCTION
public func delete(id: String) -> Completable {
    return databaseRef.child("objects").child(id).rx.removeValueAsCompletable()
        .andThen(storageRef.child("objects").child(id).rx.delete())
}

The picture may not exists on Storage, so the delete function return an error if the child doesn't exist and the Completable of the delete(id: String) function return also an error. I wan't to ignore the second function if it returns an error, is it possible ? Does a function named ignoreOnError() exists in RxSwift, or something like that ?

Thanks for your help !

There is no ignoreError() , but you can try to work your way around this with optionals. Completable.catchError can work but requires you return another valid Completable instead. It's more like "map on error".

If it works for you to just complete on error, then you're all set with catchError .

If you need to not complete on error, though, I suggest you map this to a Observable<Void> that emits .next and .completed when the Completable source sequence completes. With the power of .next , you can map errors to values instead of completion.

Let's assume you have a Observable<Void> based on your Completable :

  1. Transform your sequence into a sequence of optionals: .map(Optional.init)
  2. Transform errors in your sequence into nil : .catchErrorJustReturn(nil)
  3. Return non-nil values, effectively ignoring errors: .filter { $0 != nil }.map { $0! } .filter { $0 != nil }.map { $0! } or similar.

If you need a Completable in the end but now have a Observable<Void> , try to transform it back again: .concat(.never()).asCompletable() After all, you know the process so far produces only a single element, an error, or the completion event.

You could use .catchError { _ in .empty() } :

public func delete(id: String) -> Completable {
     databaseRef.child("objects").child(id).rx.removeValueAsCompletable()
        .andThen(storageRef.child("objects").child(id).rx.delete())
        .catchError { _ in .empty() }
}

It transforms error to empty Completable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM