这是我第一次使用执行器服务。我正在尝试从 ExecutorService 返回数据,但返回类型有问题。目前我正在从我的数据库中获取数据,这是由我的存储库调用并返回的。我正在尝试使用 ExecutorService 来执行此操作。这是我的代码
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);
问题是,ExecutorService 要求的是表达式而不是 LiveData>。
最佳答案
必须在那里传递 Runnable
并且我添加了一个秒参数 start
,因为 limit
没有用,除非知道从哪里开始从中加载,因为它在分页或寻呼机中很常见。
private MutableLiveData<List<User>> users;
public void getUsers(final int start, final int limit) {
try {
this.mIoExecutor.submit((Runnable) () -> {
List<User> data = mDao.getUsers(start, limit);
users.postValue(data);
});
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
关于android - 从 Executor 服务返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51937399/