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();
}
}
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对象并且回调。
注意:如果这个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;
}
}
打印结果为:
注意“addSource1执行了”只打印了一次,而“result =成功咯”打印了2次
如果代码改成如下:
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就是使用双层嵌套的原因
}
打印结果为:
注意“result = 成功咯”只打印了一次
如果不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就是使用双层嵌套的原因
}
打印结果如下:
注意“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));
LiveData 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 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)));
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> 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();
}