swift – 如何取消订阅观察?

swift – 如何取消订阅观察?,第1张

概述如果我有这样的东西: func foo() -> Observable<Foo> { return Observable.create { observer in // ... } } func bar() { foo().observeOn(MainScheduler.instance) .subscribeNext { 如果我有这样的东西:

func foo() -> Observable<Foo> {    return Observable.create { observer in      // ...    }  }  func bar() {    foo().observeOn(MainScheduler.instance)      .subscribeNext {        // ...      }      .adddisposableto(disposeBag)  }

如果我想稍后在bar中观察unsubscribe,我该怎么做?

更新

我知道我可以打电话处理,但根据RxSwift docs:

Note that you usually do not want to manually call dispose; this is only educational example. Calling dispose manually is usually a bad code smell.

那么取消订阅只是没有实施?我已经完成了对RxSwift代码的探索,并且在我能够理解正在发生什么的程度上,它看起来不像从订阅方法返回的disposable是任何具有有用功能的东西(除了处理).

解决方法 您将foo返回的Observable添加到disposeBag.它在取消分配时处理订阅.
您可以通过调用“手动”释放disposeBag

disposeBag = nil

你班上的某个地方.

问题编辑后:您希望有选择地取消订阅某些Observable,可能是在满足某些条件时.您可以使用另一个表示这些条件的Observable,并根据需要使用takeuntil运算符取消订阅.

//given that cancellingObservable sends `next` value when the subscription to `foo` is no longer neededfoo().observeOn(MainScheduler.instance)  .takeuntil(cancellingObservable)  .subscribeNext {    // ...  }  .adddisposableto(disposeBag)
总结

以上是内存溢出为你收集整理的swift – 如何取消订阅观察?全部内容,希望文章能够帮你解决swift – 如何取消订阅观察?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1003931.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存