MediatorLiveData#addSource之Android Architecture Components踩坑記錄

1.關(guān)于MediatorLiveData的addSource()方法
    /**
     * Starts to listen the given {@code source} LiveData, {@code onChanged} observer will be called
     * when {@code source} value was changed.
     * <p>
     * {@code onChanged} callback will be called only when this {@code MediatorLiveData} is active.
     * <p> If the given LiveData is already added as a source but with a different Observer,
     * {@link IllegalArgumentException} will be thrown.
     *
     * @param source    the {@code LiveData} to listen to
     * @param onChanged The observer that will receive the events
     * @param <S>       The type of data hold by {@code source} LiveData
     */
    @MainThread
    public <S> void addSource(LiveData<S> source, Observer<S> onChanged) {
        //新建一個(gè)Source并且將該Source的Observer傳進(jìn)去
        Source<S> e = new Source<>(source, onChanged);
        //檢查這個(gè)Source是否存在
        Source<?> existing = mSources.putIfAbsent(source, e);
        //如果存在且這個(gè)Source的Observer不等于新傳進(jìn)來的Observer就會(huì)報(bào)錯(cuò)
        if (existing != null && existing.mObserver != onChanged) {
            throw new IllegalArgumentException(
                    "This source was already added with the different observer");
        }
        if (existing != null) {//如果存在直接return
            return;
        }
        if (hasActiveObservers()) {//不存在就插入(plug)
            e.plug();
        }
    }
    void plug() {
            mLiveData.observeForever(mObserver);//observeForever()這個(gè)方法不會(huì)自動(dòng)移除银受,需要手動(dòng)停止實(shí)際它內(nèi)部調(diào)用的是observe(ALWAYS_ON, observer);
        }

        void unplug() {
            mLiveData.removeObserver(mObserver);
        }

從注釋來看革答,addSource()是add一個(gè)LiveData對象作為一個(gè)source,同時(shí)add一個(gè)Observer對象來監(jiān)聽這個(gè)LiveData的值的變化棺禾,如果有變化則會(huì)在onChange()里回調(diào)眉睹。
并且僅當(dāng)這個(gè)MediatorLiveData處于active時(shí)Observer的onChange()才會(huì)回調(diào)。

  @CallSuper
    @Override
    protected void onActive() {
        for (Map.Entry<LiveData<?>, Source<?>> source : mSources) {
            source.getValue().plug();
        }
    }

    @CallSuper
    @Override
    protected void onInactive() {
        for (Map.Entry<LiveData<?>, Source<?>> source : mSources) {
            source.getValue().unplug();
        }
    }

看到這里大概就能知道竭沫,其實(shí)這個(gè)MediatorLiveData類就是個(gè)自定義LiveData撕捍,可以觀察其他LiveData對象并且回調(diào)。

注意:如果這個(gè)LiveData已經(jīng)被add作為一個(gè)source,但是這個(gè)source沒有被remove的情況下削彬,再次調(diào)用addSource()并且傳了同一個(gè)LiveData和一個(gè)不同的Observer就會(huì)報(bào)非法數(shù)據(jù)異常全庸。例如:

 private final MediatorLiveData<String> result = new MediatorLiveData<>();

 public void setQuery(@Nonnull String originalInput){
        result.addSource(testLive, number -> {
//            result.removeSource(result1);//如果這行注釋掉,執(zhí)行到下一行就會(huì)報(bào)錯(cuò)融痛。
               result.addSource(result1, newNumber -> result.setValue("成功咯"));
            }
        });
        testLive.setValue(3);
    }
問題一:

我在閱讀官方demo NetworkBoundResource這個(gè)類的時(shí)候有個(gè)疑惑壶笼,為啥addSource()要嵌套使用呢?像上面這段代碼一樣雁刷。最終經(jīng)過實(shí)踐找到了原因
先看Fragment中的代碼

public class TestFragment extends LifecycleFragment implements Injectable {
    
    private TestModel testModel;
    private View mView;
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.search_fragment, null);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        testModel = ViewModelProviders.of(this).get(TestModel.class);//獲取ViewModel
       
        testModel.getResult().observe(this, result -> { //注冊觀察者,注意這個(gè)必須得注冊覆劈,否則ViewModel中的MediatorLiveData就不處于onActive()狀態(tài)。
            Timber.e("result ="+result.toString());
        });
        
        mView.findViewById(R.id.input).setOnClickListener(v -> {
            testModel.setQuery("test");
        });
    }
}

再來看TestModel中的代碼

public class TestModel extends ViewModel {
    private final MediatorLiveData<String> result = new MediatorLiveData<>();

    private MutableLiveData<String> testLive = new MutableLiveData<>();

    public TestModel(){

    }

    public void setQuery(@Nonnull String originalInput){
        testLive.setValue(originalInput);
        result.addSource(testLive, str -> {
            Timber.e("addSource1執(zhí)行了");
            result.removeSource(testLive);//先移除
            if(str == null){
                Timber.e("str == null");
            } else {
                result.addSource(testLive, newNumber -> result.setValue("成功咯"));//雙層嵌套沛励,前提是前面有removeSource
            }
        });
        testLive.setValue("test");//注意這里和remove就是使用雙層嵌套的原因
    }

    public LiveData<String> getResult(){
        return result;
    }
}

打印結(jié)果為:

Paste_Image.png

注意“addSource1執(zhí)行了”只打印了一次责语,而“result =成功咯”打印了2次

如果代碼改成如下:

public void setQuery(@Nonnull String originalInput){
        testLive.setValue(originalInput);
        result.addSource(testLive, str -> {
            Timber.e("addSource1執(zhí)行了");
            result.removeSource(testLive);//先移除
            if(str == null){
                Timber.e("str == null");
            } else {
//                result.addSource(testLive, newNumber -> result.setValue("成功咯"));//雙層嵌套,前提是前面有removeSource
                result.setValue("成功咯");
            }
        });
        testLive.setValue("test");//注意這里和remove就是使用雙層嵌套的原因
    }

打印結(jié)果為:

Paste_Image.png

注意“result = 成功咯”只打印了一次

如果不remove并且不嵌套addSource,如下代碼:

 public void setQuery(@Nonnull String originalInput){
        testLive.setValue(originalInput);
        result.addSource(testLive, str -> {
            Timber.e("addSource1執(zhí)行了");
//            result.removeSource(testLive);//先移除
            if(str == null){
                Timber.e("str == null");
            } else {
//                result.addSource(testLive, newNumber -> result.setValue("成功咯"));//雙層嵌套侯勉,前提是前面有removeSource
                result.setValue("成功咯");
            }
        });
        testLive.setValue("test");//注意這里和remove就是使用雙層嵌套的原因
    }

打印結(jié)果如下:

Paste_Image.png

注意“addSource1執(zhí)行了”和“result =成功咯”各執(zhí)行2次

經(jīng)過手動(dòng)幾次測試終于理解了這樣做的用意了,首先確保構(gòu)造方法中的addSource()只接收一次狀態(tài)改變的回調(diào)铝阐,就是從本地?cái)?shù)據(jù)庫查詢到結(jié)果后會(huì)回調(diào)一次址貌,loadFromDb()查詢到結(jié)果之后,在第一個(gè)addSource()中回調(diào)徘键,然后removeSource()练对,如果不需要聯(lián)網(wǎng)更新數(shù)據(jù)的話,就直接再addSource(),這樣做的目的有2個(gè)吹害,第一:之前的loadFromDb()的結(jié)果還是會(huì)在這個(gè)addSource()中回調(diào)一次(注意:就算之前dbSource()多次被setValue(),這個(gè)addSource也只會(huì)回調(diào)一次螟凭,且是最后一次setValue的結(jié)果,這樣做是保證數(shù)據(jù)是最新的)它呀,第二:保證之后數(shù)據(jù)庫每次loadFromDb()后螺男,addSource()中都能獲取到數(shù)據(jù)(且如果2次或多次setValue時(shí)間相隔很近的話棒厘,addSource中只會(huì)回調(diào)最后一次)。

如下為NetworkBoundResource類的代碼:

/**
 * A generic class that can provide a resource backed by both the sqlite database and the network.
 * <p>
 * You can read more about it in the <a >Architecture
 * Guide</a>.
 * @param <ResultType>
 * @param <RequestType>
 */
public abstract class NetworkBoundResource<ResultType, RequestType> {
    private final AppExecutors appExecutors;

    private final MediatorLiveData<Resource<ResultType>> result = new MediatorLiveData<>();

    @MainThread
    NetworkBoundResource(AppExecutors appExecutors) {
        this.appExecutors = appExecutors;
        result.setValue(Resource.loading(null));
        LiveData<ResultType> dbSource = loadFromDb();
        result.addSource(dbSource, data -> {
            result.removeSource(dbSource);
            if (shouldFetch(data)) {
                fetchFromNetwork(dbSource);
            } else {
                result.addSource(dbSource, newData -> result.setValue(Resource.success(newData)));
            }
        });
    }

    private void fetchFromNetwork(final LiveData<ResultType> dbSource) {
        LiveData<ApiResponse<RequestType>> apiResponse = createCall();
        // we re-attach dbSource as a new source, it will dispatch its latest value quickly
        result.addSource(dbSource, newData -> result.setValue(Resource.loading(newData)));
        result.addSource(apiResponse, response -> {
            result.removeSource(apiResponse);
            result.removeSource(dbSource);
            //noinspection ConstantConditions
            if (response.isSuccessful()) {
                appExecutors.diskIO().execute(() -> {
                    saveCallResult(processResponse(response));
                    appExecutors.mainThread().execute(() ->
                            // we specially request a new live data,
                            // otherwise we will get immediately last cached value,
                            // which may not be updated with latest results received from network.
                            result.addSource(loadFromDb(),
                                    newData -> result.setValue(Resource.success(newData)))
                    );
                });
            } else {
                onFetchFailed();
                result.addSource(dbSource,
                        newData -> result.setValue(Resource.error(response.errorMessage, newData)));
            }
        });
    }

    protected void onFetchFailed() {
    }

    public LiveData<Resource<ResultType>> asLiveData() {
        return result;
    }

    @WorkerThread
    protected RequestType processResponse(ApiResponse<RequestType> response) {
        return response.body;
    }

    @WorkerThread
    protected abstract void saveCallResult(@NonNull RequestType item);

    @MainThread
    protected abstract boolean shouldFetch(@Nullable ResultType data);

    @NonNull
    @MainThread
    protected abstract LiveData<ResultType> loadFromDb();

    @NonNull
    @MainThread
    protected abstract LiveData<ApiResponse<RequestType>> createCall();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末下隧,一起剝皮案震驚了整個(gè)濱河市奢人,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌淆院,老刑警劉巖何乎,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異土辩,居然都是意外死亡支救,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進(jìn)店門拷淘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來各墨,“玉大人,你說我怎么就攤上這事辕棚∮鳎” “怎么了?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵逝嚎,是天一觀的道長扁瓢。 經(jīng)常有香客問我,道長补君,這世上最難降的妖魔是什么引几? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮挽铁,結(jié)果婚禮上伟桅,老公的妹妹穿的比我還像新娘。我一直安慰自己叽掘,他們只是感情好楣铁,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著更扁,像睡著了一般盖腕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上浓镜,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天溃列,我揣著相機(jī)與錄音,去河邊找鬼膛薛。 笑死听隐,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的哄啄。 我是一名探鬼主播雅任,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼风范,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了椿访?” 一聲冷哼從身側(cè)響起乌企,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎成玫,沒想到半個(gè)月后加酵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡哭当,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年猪腕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片钦勘。...
    茶點(diǎn)故事閱讀 40,117評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡陋葡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出彻采,到底是詐尸還是另有隱情腐缤,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布肛响,位于F島的核電站岭粤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏特笋。R本人自食惡果不足惜剃浇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望猎物。 院中可真熱鬧虎囚,春花似錦、人聲如沸蔫磨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽堤如。三九已至蒲列,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間煤惩,已是汗流浹背嫉嘀。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工炼邀, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留魄揉,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓拭宁,卻偏偏與公主長得像洛退,于是被迫代替她去往敵國和親瓣俯。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容