我目前检查出以下指南:https://developer.android.com/topic/libraries/architecture/guide.htmlAndroid的体系结构组件网线
的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?
此外,为了保存到数据库中,应用了@WorkerThread,而@MainThread用于检索结果。
对于NetworkIO和本地数据库交互默认使用工作者线程是不好的做法吗?
我也看看下面的演示(GithubBrowserSample):https://github.com/googlesamples/android-architecture-components
这让我困惑,从线程的角度来看。
该演示使用了executors框架,并为networkIO定义了一个包含3个线程的固定池,但是在演示中,仅为一个调用定义了一个工作任务,即FetchNextSearchPageTask
。所有其他网络请求似乎都在主线程上执行。
有人可以澄清理由吗?
感谢您的澄清并指出改进的可能性。我确实误解了注释,即网络请求是通过Retrofit异步执行的,并且仅仅是主线程上的包装。 – Trace