加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 如何取消订阅观察?

发布时间:2020-12-14 04:34:23 所属栏目:百科 来源:网络整理
导读:如果我有这样的东西: func foo() - ObservableFoo { return Observable.create { observer in // ... } } func bar() { foo().observeOn(MainScheduler.instance) .subscribeNext { // ... } .addDisposableTo(disposeBag) } 如果我想稍后在bar中观察unsubs
如果我有这样的东西:

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 needed

foo().observeOn(MainScheduler.instance)
  .takeUntil(cancellingObservable)
  .subscribeNext {
    // ...
  }
  .addDisposableTo(disposeBag)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读