RxSwift-DisposeBag垃圾袋

DisposeBag垃圾袋分析, demo运行如下:

self.intervalOB = Observable.interval(.seconds(1), scheduler: MainScheduler.init())
        self.intervalOB.subscribe(onNext: { (num) in
            self.showSencondNum.text = String(num)
        }).disposed(by: disposeBag)
        
        _ = self.stopAction.rx.tap.subscribe(onNext: {
            print("点击按钮")
            self.disposeBag = DisposeBag()
        })

subscribe订阅序列的时候返回一个销毁者DisposeBase,当调用.disposed(by: disposeBag)的时候,会调用insert()

public func disposed(by bag: DisposeBag) {
        bag.insert(self)
    }

实际是插入到数组_disposables = [Disposable]()

 fileprivate var _disposables = [Disposable]()
    fileprivate var _isDisposed = false
    /// Constructs new empty dispose bag.
    public override init() {
        super.init()
    }
    /// Adds `disposable` to be disposed when dispose bag is being deinited.
    ///
    /// - parameter disposable: Disposable to add.
    public func insert(_ disposable: Disposable) {
        self._insert(disposable)?.dispose()
    }
    private func _insert(_ disposable: Disposable) -> Disposable? {
        self._lock.lock(); defer { self._lock.unlock() }
        if self._isDisposed {
            return disposable
        }
        self._disposables.append(disposable)
        return nil

当随着对象的生命周期结束,会调用deinit(),内部调用dispose()

deinit {
        self.dispose()
    }

紧接着会循环调用disposable.dispose(),源码分析如下:

 private func dispose() {
        let oldDisposables = self._dispose()

        for disposable in oldDisposables {
            disposable.dispose()
        }
    }

实现销毁者的销毁;

你可能感兴趣的:(RxSwift-DisposeBag垃圾袋)