从执行器服务返回数据

时间:2018-08-20 19:33:16

标签: android executorservice android-room android-livedata android-jetpack

这是我第一次使用Executor服务,我试图从executor服务返回数据,但在返回类型方面遇到麻烦。目前,我正在从数据库中获取数据,这由我的存储库调用并返回。我正在尝试使用执行程序服务来执行此操作。这是我的代码,

public LiveData<List<User>> getUsers(int limit) {
    try{
        return mIoExecutor.submit(mDao.getUsers(limit), LiveData<List<User>)
    }catch (InterruptedException | ExecutionException e){
        e.printStackTrace();
        return null;
    }

}

我的数据库

 @Query("select * from smiley ORDER BY name, RANDOM() LIMIT :limit")
LiveData<List<User>> getUsers(int limit);

问题是执行服务正在请求表达式而不是LiveData>

2 个答案:

答案 0 :(得分:1)

您需要在此处传递Runnable ...

private MutableLiveData<List<User>> users;

public void getUsers(final int start, final int limit) {
    try {

        this.mIoExecutor.submit(new Runnable() {
            @Override
            public void run() {

                /* background thread */
                List<User> data = mDao.getUsers(start, limit);
                users.postValue(data);   
            }
        });

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}  

并且我添加了一个秒参数start,因为limit毫无用处,除非知道从何处开始加载,因为通常将其与分页或无穷大的寻呼机(垂直连接)一起使用

答案 1 :(得分:0)

可以使用多种方法提交任务。 execute() submit() 这两个基本参数。

主要区别如下:

  • void execute(Runnable command) -执行Runnable任务
  • Future<?> submit(Runnable task) -执行Runnable任务,返回代表该任务的Future
  • <T> Future<T> submit(Callable<T> task) -执行一个Callable任务,返回代表该任务的未决结果的Future

您正确使用的是 submit() 方法,该方法返回有关已执行任务的信息。

在检索submit()方法返回的信息时,请注意以下几点:

  1. 方法 submit()返回Future对象。为了检索有关任务的信息,我们需要使用Future方法从get()对象中检索信息。有两个可用:
    • V get()
    • V get(long timeout, TimeUnit unit)
  2. 在信息请求之时该任务可能尚未完成。我们可以使用Future.isDone()方法来确保任务完成(请注意,如果任务引发异常或被取消,该方法也将返回true)。
  3. 我们需要提交一个Callable对象。如上所述,有两种submit()方法,一种接受 Runnable ,一种接受 Callable 。两者都是功能性接口,主要区别在于:
    • Runnable-它是run()方法,不接受任何值并返回值,它不能引发异常
    • Callable-它的call()方法返回一个值并可以引发异常

get()对象上调用Future,将返回与call()方法定义的返回类型相同的返回类型;如果提交了null对象,则返回Runnable (方法run()不返回任何值)。