Proper way to dispose a one-off observable in RxSwift

前端 未结 1 1347
误落风尘
误落风尘 2021-02-05 06:19

I have an observable that I only want to kick off once. The docs say:

Using dispose bags or takeUntil operator is a robust way of making sure resources ar

相关标签:
1条回答
  • 2021-02-05 06:49

    Both DiposeBag and takeUntil are used to cancel a subscription prior to receiving the .Completed/.Error event.

    When an Observable completes, all the resources used to manage subscription are disposed of automatically.

    As of RxSwift 2.2, You can witness an example of implementation for this behavior in AnonymousObservable.swift

    func on(event: Event<E>) {
        switch event {
        case .Next:
            if _isStopped == 1 {
                return
            }
            forwardOn(event)
        case .Error, .Completed:
            if AtomicCompareAndSwap(0, 1, &_isStopped) {
                forwardOn(event)
                dispose()
            }
        }
    }
    

    See how AnonymousObservableSink calls dispose on itself when receiving either an .Error or a .Completed event, after forwarding the event.

    In conclusion, for this use case, _ = is the way to go.

    0 讨论(0)
提交回复
热议问题