RxSwift: returns a new observable with an error

I have a function that returns a Bool Observable depending on whether it was normal 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? } 
+6
source share
3 answers
 just<E>(element: E) -> Observable<E> 

Returns an observable sequence containing one element. Instead, you should use something like this:

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

The Create method creates an observable sequence from the specified implementation of the subscription method.

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 an action that is called if you want to abort it. Say that you leave your view controller or the application must be executed using the service, and you will no longer need to call this request. Its great for downloading videos or something more. You can do request.cancel (), which will clear all resources when you are done with it. This is caused by either a termination or an error.

+8
source

To create observables, there is a create function. You can use it as follows:

 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 }) } 
+2
source

Use the resulting result as the observed 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)) } 
0
source

All Articles