我目前正在查看以下指南:https://developer.android.com/topic/libraries/architecture/guide.html
网络绑定资源类:
// 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?
此外,保存到数据库时应用@WorkerThread,而检索结果时应用@MainThread。
默认情况下,对于网络I/O和本地数据库交互使用工作线程是否是不良实践?
我还在查看以下演示 (GithubBrowserSample):https://github.com/googlesamples/android-architecture-components
从线程角度来看,这让我感到困惑。
演示使用执行器框架,并为networkIO定义了一个具有3个线程的固定池,但在演示中只为一次调用定义了一个worker任务,即FetchNextSearchPageTask
。所有其他网络请求似乎都在主线程上执行。
能否有人解释一下其原理?