android - android Paging Library中Executor的真正用途是什么?

标签 android paging threadpoolexecutor

我见过大多数在 DataSource 类中使用 Executor 的示例,这些类通常从 ViewModel 传递到 DataSourceFactory,然后传递到 DataSource 类。我如何使用 executor。使用 Executor 有什么好处/优势。

View 模型

public FooViewModel{

public FooViewModel() {

    executor = Executors.newFixedThreadPool(5);
    //pasing executor here.
    FooDataSourceFactory itemDataSourceFactory = new 
   FooDataSourceFactory(executor);


}

数据源工厂

public class FooDataSourceFactory extends DataSource.Factory {
private FooDataSource itemDataSource;
private Executor executor;
//creating the mutable live data
private MutableLiveData<FooDataSource> itemLiveDataSource = new 
MutableLiveData<>();

public FooDataSourceFactory(Executor executor) {
    this.executor = executor;
}


@Override
public DataSource create() {
    //passing executor here..
    itemDataSource = new FooDataSource(executor);

    //posting the dataSource to get the values
    itemLiveDataSource.postValue(itemDataSource);

    //returning the dataSource
    return itemDataSource;

.................
}

数据源

public class FooDataSource { 

 FooDataSource(Executor executor){
       //don't know what to do with executor
    }
}

最佳答案

Executor

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new RunnableTask()).start() for each of a set of tasks, you might use: executor.execute(runnable);

在分页库中,目标是异步执行所有操作。
Executor 可以帮助您轻松插入和检索异步数据,而无需显式使用线程。

如果您正在开发具有 MVVM 架构的应用程序,您可能有一些“存储库”类来处理本地数据和/或 api 调用。在这种情况下,建议使用执行程序查询您的数据库。

您还可以使用执行程序来观察分页列表,以防您希望在数据更改时不在主线程上执行某些操作。


在您的特定情况下,您可能不需要 `DataSource` 和 `DataSourceFactory` 中的执行程序。 这取决于您在这些类(class)中所做的事情。 如果你从互联网上获取数据,有很多像 [volley][2] 和 [retrofit2][3] 这样异步执行 http 调用的库,所以不需要执行程序。

从本地数据库检索数据时,如 Room :

Out of the box room doesn't support database access on the main thread so the executor is there to ensure the work is done on a separate thread. reference

希望我的回答对您有所帮助。

关于android - android Paging Library中Executor的真正用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401502/

相关文章:

android - Gradle 无法解析我的任何依赖项

android - BlurBehind - 在 Android Studio 依赖项中找不到

javascript - 分页和过滤如何很好地工作?

java - 线程池最大线程数不正确

java - 当 corePoolSize = 0 时,ScheduledExecutorService 消耗 100% CPU

android - react native 资源问题

java - 带有 switch case 语句的 Android Studio 1.1 警告

asp.net - Gridview 中的分页不起作用 第二页数据未显示数据?

javascript - 富文本编辑器[所见即所得],使用 javascript 进行分页

java - 如何创建一个 ThreadPoolExecutor 来根据需要创建线程并在适用时使它们过期?