Closed Joslyn-Chen closed 6 years ago
In the GithubBrowserSample you can see the NetworkBoundResource
private void fetchFromNetwork(final LiveData<ResultType> dbSource) {
// there is remote callback,return LiveData
LiveData<ApiResponse<RequestType>> apiResponse = createCall();
// we re-attach dbSource as a new source, it will dispatch its latest value quickly
result.addSource(dbSource, newData -> 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 -> setValue(Resource.success(newData)))
);
});
} else {
onFetchFailed();
result.addSource(dbSource,
newData -> setValue(Resource.error(response.errorMessage, newData)));
}
});
}
the createCall() is the remote func to loadSource , this sample not use RxjavaCallAdapter you can see this LiveDataCallAdapter。
the LiveDataCallAdapter
change the retrofit callback to a Livedata with ApiResponse,this apiresponse hold the data and the data status.
I dont know is helpful for you . I am not good an english .
@alittlecup 主要是不明白这些result.addSource里面的内容,如果能用retrofit请求的话应该能看懂。
我要是知道你能说中文何必去谷歌翻译。
result.addSource,就是添加一个响应的依赖关系,跟Rx的map差不多的意思,你可以看一下具体的源码
@alittlecup 谢谢。文档里还有2段不懂。 1、Note: If you are already using a library like RxJava or Agera, you can continue using them instead of LiveData. But when you use them or other approaches, make sure you are handling the lifecycle properly such that your data streams pause when the related LifecycleOwner is stopped and the streams are destroyed when the LifecycleOwner is destroyed. You can also add the android.arch.lifecycle:reactivestreams artifact to use LiveData with another reactive streams library (for example, RxJava2). 这意思是RxJava2可以替代LiveData?如果可以替代,怎么解决生命周期问题。 2、There are 2 common solutions for this use case: Change getUser to return a LiveData that includes the status of the network operation. An example implementation is provided in the Addendum: exposing network status section. Provide another public function in the repository class that can return the refresh status of the User. This option is better if you want to show the network status in your UI only in response to explicit user action (like pull-to-refresh). 这段话没理解到,可能是翻译不准确吧
第一段的意思就是,如果你项目里面已经有Rx这种,那就就可以继续使用,不过需要注意下生命周期 等等。。然后是你也可以添加android.arch.lifecycle:reactivestreams 这个库,让LiveData和其他的响应库一起使用。这个库里面有一个转换函数,就是可以将publisher转化成LiveData.
第二段是你是在哪里看到的?你可以加一个群,MVVM交流群QQ:523344807
How to effectively expose the network status (for example: network exception, is loading ...). I do not really understand NetworkBoundResource.