MediatorLiveData#addSource踩坑记录

1.关于MediatorLiveData的addSource()方法

    /**
     * Starts to listen the given {@code source} LiveData, {@code onChanged} observer will be called
     * when {@code source} value was changed.
     * 

* {@code onChanged} callback will be called only when this {@code MediatorLiveData} is active. *

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 The type of data hold by {@code source} LiveData */ @MainThread public void addSource(LiveData source, Observer onChanged) { //新建一个Source并且将该Source的Observer传进去 Source e = new Source<>(source, onChanged); //检查这个Source是否存在 Source existing = mSources.putIfAbsent(source, e); //如果存在且这个Source的Observer不等于新传进来的Observer就会报错 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(); } } 内部类 Source void plug() { mLiveData.observeForever(mObserver);//observeForever()这个方法不会自动移除,需要手动停止实际它内部调用的是observe(ALWAYS_ON, observer); } void unplug() { mLiveData.removeObserver(mObserver); }

从注释来看,addSource()是add一个LiveData对象作为一个source, 同时add一个Observer对象来监听这个LiveData的值的变化,如果有变化则会在onChange()里回调。并且仅当这个MediatorLiveData处于active时Observer的onChange()才会回调。

 

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

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

看到这里大概就能知道,其实这个MediatorLiveData类就是个自定义LiveData,可以观察其他LiveData对象并且回调。

ReportFragment#onStart() -> ReportFragment#dispatch() -> ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event) -> LifecycleRegistry#moveToState() -> LifecycleRegistry#sync() -> LifecycleRegistry#forwardPass(lifecycleOwner) -> ObserverWithState#observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)) -> LiveData#onStateChanged() -> LiveData#activeStateChanged() -> LiveData#onActive()

所以代码里编写了

testModel.getResult().observe(this, result -> {
    // ......         
});

就会执行上面的onActive()方法,此时的mSources的大小为0.

注意:如果这个LiveData已经被add作为一个source, 但是这个source没有被remove的情况下,再次调用addSource()并且传了同一个LiveData和一个不同的Observer就会报非法数据异常。例如:

 

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

 public void setQuery(@Nonnull String originalInput){
        result.addSource(testLive, number -> {
//            result.removeSource(result1);//如果这行注释掉,执行到下一行就会报错。
               result.addSource(result1, newNumber -> result.setValue("成功咯"));
            }
        });
        testLive.setValue(3);
    }

问题一:

我在阅读官方demo NetworkBoundResource这个类的时候有个疑惑,为啥addSource()要嵌套使用呢?像上面这段代码一样。最终经过实践找到了原因
先看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 -> { //注册观察者,注意这个必须得注册,否则ViewModel中的MediatorLiveData就不处于onActive()状态。
            Timber.e("result ="+result.toString());
        });
        
        mView.findViewById(R.id.input).setOnClickListener(v -> {
            testModel.setQuery("test");
        });
    }
}

再来看TestModel中的代码

 

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

    private MutableLiveData testLive = new MutableLiveData<>();

    public TestModel(){

    }

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

    public LiveData getResult(){
        return result;
    }
}

打印结果为:

MediatorLiveData#addSource踩坑记录_第1张图片

注意“addSource1执行了”只打印了一次,而“result =成功咯”打印了2次

此时
void plug() {
    mLiveData.observeForever(this);
}
的执行流程如下:

1⃣️、LiveData#observeForever() -> ObserverWrapper#activeStateChanged() -> ObserverWrapper#dispatchingValue() -> ObserverWrapper#considerNotify() -> observer.mObserver.onChanged((T) mData) 也就是此处MediatorLiveData$Source#onChanged() 打印了addSource1执行了,

2⃣️、接着执行result.removeSource() -> Source#unplug() 移除MediatorLiveData,

3⃣️、接着又执行了result.addSource()又把上面1⃣️的流程走了一遍打印result = 成功咯

4⃣️、最后执行testLive.setValue("test");  LiveData#setValue() -> LiveData#dispatchingValue() -> LiveData#considerNotify() -> MediatorLiveData$Source#onChanged() 打印result = 成功咯

如果代码改成如下:

 

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

打印结果为:

MediatorLiveData#addSource踩坑记录_第2张图片

注意“result = 成功咯”只打印了一次, 因为result.removeSource()后testLive没有被TestFragment观察了,所以没有打印输出。

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

 

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

打印结果如下:

MediatorLiveData#addSource踩坑记录_第3张图片

注意“addSource1执行了”和“result =成功咯”各执行2次

经过手动几次测试终于理解了这样做的用意了,首先确保构造方法中的addSource()只接收一次状态改变的回调,就是从本地数据库查询到结果后会回调一次,loadFromDb()查询到结果之后,在第一个addSource()中回调,然后removeSource(),如果不需要联网更新数据的话,就直接再addSource(), 这样做的目的有2个,第一:之前的loadFromDb()的结果还是会在这个addSource()中回调一次(注意:就算之前dbSource()多次被setValue(),这个addSource也只会回调一次,且是最后一次setValue的结果,这样做是保证数据是最新的),第二:保证之后数据库每次loadFromDb()后,addSource()中的监听都能收到回调取到数据(且如果2次或多次setValue时间相隔很近的话,addSource中只会回调最后一次)。

如下为NetworkBoundResource类的代码:

 

/**
 * A generic class that can provide a resource backed by both the sqlite database and the network.
 * 

* You can read more about it in the Architecture * Guide. * @param * @param */ public abstract class NetworkBoundResource { private final AppExecutors appExecutors; private final MediatorLiveData> result = new MediatorLiveData<>(); @MainThread NetworkBoundResource(AppExecutors appExecutors) { this.appExecutors = appExecutors; result.setValue(Resource.loading(null)); // 观察者(LifecycleOwner)会接收到回调 LiveData dbSource = loadFromDb(); // dbSource内部setValue()修改mVersion的值,后面的addSource时就会跳过 LiveData#considerNotify()的语句if (observer.mLastVersion >= mVersion) { return; } result.addSource(dbSource, data -> { // 监听方法只会在dbSource.setValue()后调用,data和下面的newData的值都是上面dbSource.setValue()赋的值 result.removeSource(dbSource); // 能够执行onChanged()说明dbSource最近执行了setValue()了 if (shouldFetch(data)) { fetchFromNetwork(dbSource); } else { result.addSource(dbSource, newData -> result.setValue(Resource.success(newData))); // 显示本地数据 } }); } private void fetchFromNetwork(final LiveData dbSource) { LiveData> 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))); // 先显示本地数据,newData就是dbSource最近setValue()的值 result.addSource(apiResponse, response -> { // response是aipResponse最近一次setValue的值 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))); // 这里的newData就是loadFromDb()这个liveData.setValue()的值 ); }); } else { onFetchFailed(); result.addSource(dbSource, newData -> result.setValue(Resource.error(response.errorMessage, newData))); // addSource()的目的是可以服用dbSource的setValue()的值 ??? } }); } protected void onFetchFailed() { } public LiveData> asLiveData() { return result; } @WorkerThread protected RequestType processResponse(ApiResponse 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 loadFromDb(); @NonNull @MainThread protected abstract LiveData> createCall(); }

 

你可能感兴趣的:(android知识点,LiveData)