我目前正在查看以下指南:https://developer.android.com/topic/libraries/architecture/guide.html
networkBoundResource类:
// ResultType: Type for the Resource data
// RequestType: Type for the API response
public abstract class NetworkBoundResource<ResultType, RequestType> {
// Called to save the result of the API response into the database
@WorkerThread
protected abstract void saveCallResult(@NonNull RequestType item);
// Called with the data in the database to decide whether it should be
// fetched from the network.
@MainThread
protected abstract boolean shouldFetch(@Nullable ResultType data);
// Called to get the cached data from the database
@NonNull @MainThread
protected abstract LiveData<ResultType> loadFromDb();
// Called to create the API call.
@NonNull @MainThread
protected abstract LiveData<ApiResponse<RequestType>> createCall();
// Called when the fetch fails. The child class may want to reset components
// like rate limiter.
@MainThread
protected void onFetchFailed() {
}
// returns a LiveData that represents the resource
public final LiveData<Resource<ResultType>> getAsLiveData() {
return result;
}
}
我在这里对线程的使用有点困惑
为什么@MainThread适用于networkIO?
此外,为了保存到db,应用@WorkerThread,而@MainThread用于检索结果。
默认情况下,为NetworkIO和本地数据库交互使用工作线程是不好的做法吗?
我还要查看以下演示(GithubBrowserSample):https://github.com/googlesamples/android-architecture-components
从线程的角度来看,这让我感到困惑
该演示使用执行程序框架,并为networkIO定义了一个包含3个线程的固定池,但在演示中,只为一个调用定义了一个工作任务,即FetchNextSearchPageTask
。所有其他网络请求似乎都在主线程上执行。
有人可以澄清理由吗?