我目前檢查出以下指南: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