[英]Usage of executor in android architecture components
public class UserRepository {
private final Webservice webservice;
private final UserDao userDao;
private final Executor executor;
@Inject
public UserRepository(Webservice webservice, UserDao userDao, Executor executor) {
this.webservice = webservice;
this.userDao = userDao;
this.executor = executor;
}
public LiveData<User> getUser(String userId) {
refreshUser(userId);
// Returns a LiveData object directly from the database.
return userDao.load(userId);
}
private void refreshUser(final String userId) {
// Runs in a background thread.
executor.execute(() -> {
// Check if user data was fetched recently.
boolean userExists = userDao.hasUser(FRESH_TIMEOUT);
if (!userExists) {
// Refreshes the data.
Response<User> response = webservice.getUser(userId).execute();
// Check for errors here.
// Updates the database. The LiveData object automatically
// refreshes, so we don't need to do anything else here.
userDao.save(response.body());
}
});
}
}
上面的代碼是“應用架構指南”的一部分,來自 Android 文檔,使用架構組件。 在refreshUser方法中,如果緩存中不存在數據,則使用改造從網絡中獲取數據。
我的問題是:為什么他們為此使用執行程序? Retrofit 本身已經能夠異步運行網絡請求。
請在這個例子中為我澄清 Executor 到底是什么以及它的需求。
開箱即用的房間不支持主線程上的數據庫訪問,因此執行程序在那里確保工作在單獨的線程上完成。
通過使用執行器,他們還選擇使用同步改造調用,這將阻塞正在執行的線程。
在您引用的執行程序的代碼中,執行程序是一個 SingleThreadExecutor,這實際上創建了一個工作線程來執行其工作,在這種情況下,它將執行 Room DB 操作以及處理同步改造調用。
連同 newSingleThreadExecutor 的官方文檔: https ://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor ()
Executor 究竟是什么?
通常使用 Executor 而不是顯式創建線程。 例如,而不是調用new Thread(new RunnableTask()).start()
為每一個組任務,您可以使用:
Executor executor = someExecutor(); // any class implementing `Executor` interface
executor.execute(new Runnable1());
executor.execute(new Runnable2());
他們為什么要為此使用執行程序? Retrofit 本身已經能夠異步運行網絡請求。
他們使用它從主線程切換到后台工作線程,以執行數據庫操作,因為默認情況下, Room架構組件不允許在MainThread
上進行查詢。
Retrofit能夠執行異步網絡請求,但他們在這里執行同步網絡請求,之后他們只是使用 Room 組件在本地數據庫上執行插入操作。
有關 Executor 框架的更多信息,您可以按照本指南進行操作: https : //developer.android.com/reference/java/util/concurrent/Executor
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.