Godfather
Godfather

Reputation: 4330

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?
}

Upvotes: 13

Views: 23457

Answers (3)

Tommy Sadiq Hinrichsen
Tommy Sadiq Hinrichsen

Reputation: 804

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))
}

Upvotes: 2

Alexander Guschin
Alexander Guschin

Reputation: 469

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.

Upvotes: 12

Serg Dort
Serg Dort

Reputation: 487

For creating observables there is create function. You can use it like this:

func test() -> Observable<Bool> {
   return create({ (observer) -> Disposable in
//      Some condition
      observer.onNext(true)
//      Some other condition
      observer.onNext(false)
//      Some other condition
      observer.onError(NSError(domain: "My domain", code: -1, userInfo: nil))
//      Some other condition
      observer.onCompleted()

      return AnonymousDisposable {
//         Dispose resources here
      }
//      If u have nothing to dipose use NopDisposable.instance


   })
}

Upvotes: 4

Related Questions