The right way to dispose of disposable items within the observable

I have an HTTPService that returns an Observable<NSData> . My goal is to compose this service in another service, ServiceA , which converts this data for my use case. Using Observable.create in RxSwift 2.0.0-rc.0 in ServiceA , it is fairly straight forward. My question is how to properly handle the one-time device returned from an HTTPService subscription.

If I do nothing, I get a compilation warning indicating that result of call is unused : http://git.io/rxs.ud . I understand that reading that if I am not doing anything is probably good: (where is the xs mentioned below, let xs: Observable<E> ....

If xs completes in a predictable way with the message Completed or Error, without processing the Disposable subscription, there will be no leakage of resources, but it is still preferable, because in this way the calculation of the element stops at a predictable moment.

So, here is how I am now addressing him, and also where I wonder if I am doing it right or if something is misunderstood.

 public struct ServiceA{ public static func changes() -> Observable<ChangeSet>{ return Observable.create{ observable in // return Observable<NSData> let request = HTTPService.get("https://httpbin.org/get") let disposable = request.subscribe( onNext: { data in // Do more work to transform this data // into something meaningful for the application. // For example purposes just use an empty object observable.onNext(ChangeSet()) observable.onCompleted() }, onError:{ error in observable.onError(error) }) // Is this the right way to deal with the // disposable from the subscription in this situation? return AnonymousDisposable{ disposable.dispose() } } } } 
+6
source share
1 answer

As the documentation says

the subscribe function returns a one-time subscription, which can be used to cancel calculations and free resources.
The preferred way to end these free calls is to use .addDisposableTo (disposeBag) or in some equivalent way. When the disposeBag released, the subscription will be automatically located.

Actually your example looks fine in terms of rules, but it's pretty bad;) (It would also be nice if you just returned this disposable ):

 public static func changes() -> Observable<ChangeSet>{ return Observable.create{ observable in // return Observable<NSData> let request = HTTPService.get("https://httpbin.org/get") return request.subscribe( onNext: { data in // Do more work to transform this data // into something meaningful for the application. // For example purposes just use an empty object observable.onNext(ChangeSet()) observable.onCompleted() }, onError:{ error in observable.onError(error) }) } 

But how do you return Observeble , I wonder why you just do not use the map operator?

In your example, it would be something like this:

 public static func changes() -> Observable<ChangeSet> { return HTTPService.get("https://httpbin.org/get") .map(ChangeSet.init) } 
+2
source

All Articles