这是我第一次使用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>
答案 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()
方法返回的信息时,请注意以下几点:
submit()
返回Future
对象。为了检索有关任务的信息,我们需要使用Future
方法从get()
对象中检索信息。有两个可用:
V get()
V get(long timeout, TimeUnit unit)
Future.isDone()
方法来确保任务完成(请注意,如果任务引发异常或被取消,该方法也将返回true)。 Callable
对象。如上所述,有两种submit()
方法,一种接受 Runnable
,一种接受 Callable
。两者都是功能性接口,主要区别在于:
Runnable
-它是run()
方法,不接受任何值并返回值,它不能引发异常Callable
-它的call()
方法返回一个值并可以引发异常在get()
对象上调用Future
,将返回与call()
方法定义的返回类型相同的返回类型;如果提交了null
对象,则返回Runnable
(方法run()
不返回任何值)。