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?
}
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))
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With