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é)果為:
注意“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é)果為:
注意“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é)果如下:
注意“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();
}