【发布时间】:2018-01-13 20:01:21
【问题描述】:
我目前正在查看以下指南: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;
}
}
我对线程的使用有点困惑。
为什么这里要为networkIO申请@MainThread?
此外,为了保存到数据库中,应用 @WorkerThread,而 @MainThread 用于检索结果。
默认情况下使用工作线程进行 NetworkIO 和本地数据库交互是不好的做法吗?
我还在查看以下演示 (GithubBrowserSample):https://github.com/googlesamples/android-architecture-components
从线程的角度来看,这让我感到困惑。
该演示使用 executors 框架,并为 networkIO 定义了一个具有 3 个线程的固定池,但是在演示中只为一次调用定义了一个工作任务,即FetchNextSearchPageTask。所有其他网络请求似乎都在主线程上执行。
有人可以澄清原因吗?
【问题讨论】:
标签: java android multithreading architecture