android - android架构组件中executor的使用

标签 android multithreading android-room 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());
        }
    });
}
}

上面的代码是"Guide to app architecture"的一部分,来自 Android 文档,使用架构组件。在 refreshUser 方法中,如果缓存中不存在数据,它们会使用改进从网络中获取数据。

我的问题是:为什么他们为此使用执行器? Retrofit 本身已经能够异步运行网络请求。

请为我说明这个示例中执行器到底是什么以及它的需要。

最佳答案

开箱即用的房间不支持主线程上的数据库访问,因此执行程序在那里确保工作在单独的线程上完成。

通过使用执行器,他们还选择使用同步改造调用,这将阻塞正在执行的线程。

在您引用的代码中,执行器是一个 SingleThreadExecutor,这实际上创建了一个工作线程来执行其工作,在这种情况下,它将执行 Room DB 操作以及处理同步改造调用。

这是上例中执行器的链接。 https://github.com/PhilippeBoisney/GithubArchitectureComponents/blob/98e0a048791f18646c730323c242c670c3eaf453/app/src/main/java/com/boisneyphilippe/githubarchitecturecomponents/di/module/AppModule.java#L48

连同 newSingleThreadExecutor 的官方文档: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor()

关于android - android架构组件中executor的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164957/

相关文章:

java - 在 Android Studio 中找不到 JDBC 类

java lang Nullpointerexception 更新谷歌服务后

java - 非阻塞 API 是如何工作的?

android - 房间可流动缓存

插入新行时 Android Room FOREIGN KEY 约束失败(代码 787)

java - 即使关闭键盘,Phonegap android 导航栏也不会隐藏

android - 将图像从 JSON 解析为 Android 中的 ListView

Java 管道输入/输出流通信中存在大量延迟

java - 直接在线程对象上调用Runnable的run()方法

android - 房间: DAO query that removes duplicates given multiple columns as criteria