Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift: Return a new observable with an error

I have a function that return a Bool Observable depending if it was ok or not.

func test() -> Observable<Bool> {
   if everythingIsOk {
      return just(true)
   }
   return just(false) <- how can i here return a custom error to retrieve what failed?
}
like image 973
Godfather Avatar asked Dec 18 '15 08:12

Godfather


Video Answer


2 Answers

Use a result enum as your observable value.

public enum Result<Value> {
    case success(Value)
    case failure(Error)
}

func test() -> Observable<Result<Bool>> {
   if everythingIsOk {
      return just(.success(true))
   }

   let error = ...
   return just(.failure(error))
}
like image 128
Tommy Sadiq Hinrichsen Avatar answered Sep 28 '22 06:09

Tommy Sadiq Hinrichsen


just<E>(element: E) -> Observable<E>

Returns an observable sequence that contains a single element. Instead, you should use something like that:

create<E>(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E>

Create method creates an observable sequence from a specified subscribe method implementation.

In your case:

private let realm = try! Realm()

func save(customObject: CustomObject) -> Observable<Bool> {
    return create({ observer -> Disposable in
        do {
            try self.realm.write {
                self.realm.add(customObject, update: true)
                observer.onNext(true)
                observer.onCompleted()
            }
        } catch {
            // .Error sequence will be automatically completed
            observer.onError(NSError(domai...)
        }

        // if realm.write is sync task(by default it is, as I know) you can actually return NopDisposable
        return NopDisposable.instance
        // otherwise you should cancel write transaction in AnonymousDisposable
    })
}

AnonymousDisposable is the action that’s called in case you want to get interrupted. Say you leave your view controller or the app needs to be done with the service and you don’t need to call this request any longer. It’s great for video uploads or something much larger. You can do request.cancel() which cleans up all the resources when you’re done with it. This gets called on either completion or error.

like image 21
Alexander Guschin Avatar answered Sep 28 '22 07:09

Alexander Guschin