如果我什么都不做,我得到编译时间警告,调用结果未使用:http://git.io/rxs.ud.我从阅读中理解,如果我什么也不做,那可能没问题:(下面提到的xs是让xs:Observable< E> ;. ...
In case xs terminates in a predictable way with Completed or Error message,not handling subscription disposable won’t leak any resources,but it’s still preferred way because in that way element computation is terminated at predictable moment.
所以这就是我目前正在解决的问题,也是我想知道我是否正确地做到这一点,或者我是否误解了一些问题.
public struct ServiceA{ public static func changes() -> Observable<ChangeSet>{ return Observable.create{ observable in // return's 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() } } } }
解决方法
subscribe function returns a subscription disposable that can be used to cancel computation and free resources.
Preferred way of terminating these fluent calls is by using
.adddisposableto(disposeBag) or in some equivalent way.
WhendisposeBag
gets deallocated,subscription will be automatically
disposed.
实际上你的例子在规则方面看起来很好,但它很糟糕;)(也可以,如果你只是返回这个一次性):
public static func changes() -> Observable<ChangeSet>{ return Observable.create{ observable in // return's 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) }) }
但是当你回到Observeble时,我想知道,为什么你不只是使用地图运算符?
在您的示例中,它将是这样的:
public static func changes() -> Observable<ChangeSet> { return HTTPService.get("https://httpbin.org/get") .map(ChangeSet.init) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。