Rxjava CompositeDisposable 注意事項(xiàng)

Rxjava CompositeDisposable 是用來管理disposable的容器,之前的用法是生成disposable的時(shí)候add到CompositeDisposable里面,在ondestroy的時(shí)候CompositeDisposable調(diào)用dispose注銷。
CompositeDisposable dispose的源碼中

public void dispose() {
        if (!this.disposed) {
            OpenHashSet set;
            synchronized(this) {
                if (this.disposed) {
                    return;
                }
              //標(biāo)記為disposed
                this.disposed = true;
                set = this.resources;
                this.resources = null;
            }
            this.dispose(set);
        }
    }

之后add的時(shí)候

 public boolean add(@NonNull Disposable disposable) {
        ObjectHelper.requireNonNull(disposable, "disposable is null");
  //  已經(jīng)被標(biāo)記為disposed 所以不會(huì)進(jìn)去
        if (!this.disposed) {
            synchronized(this) {
                if (!this.disposed) {
                    OpenHashSet<Disposable> set = this.resources;
                    if (set == null) {
                        set = new OpenHashSet();
                        this.resources = set;
                    }

                    set.add(disposable);
                    return true;
                }
            }
        }
    // 直接走這里,傳進(jìn)來的disposable直接被dispose()
        disposable.dispose();
        return false;
    }

所以\color{red}{dispose()之后add()的disposable直接被dispose()}(這個(gè)字體真丑)
開發(fā)過程中遇到create出來的single在第二次進(jìn)去之后死活調(diào)不到subscribe里面,查了2個(gè)小時(shí)才發(fā)現(xiàn)的。
如果CompositeDisposable 對(duì)象的生命周期比較長,后續(xù)還需要繼續(xù)使用,就使用CompositeDisposable.clear()來代替。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容