This is my first time working with executor services. I am trying to return data from an ExecutorService, while having trouble with the return type. Currently I am getting data from my database, this is called by my repository and returned. I am trying to use an ExecutorService to do this. Here is my code
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;
}
}
and my database
@Query("select * from smiley ORDER BY name, RANDOM() LIMIT :limit")
LiveData<List<User>> getUsers(int limit);
The issue is, that ExecutorService is asking for an expression instead of LiveData>.
One has to pass Runnable there and I've added a seconds parameter start, because limit is useless, unless knowing where to start loading from, as it is common for pagination or a pager.
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();
}
}
There are multiple methods one can use for submitting the task. The two basic ones being execute() and submit().
Here are the key differences:
void execute(Runnable command) - executes a Runnable taskFuture<?> submit(Runnable task) - executes a Runnable task, returns a Future representing the task<T> Future<T> submit(Callable<T> task) - executes a Callable task, returns a Future representing the pending results of the taskYou are correctly using a submit() method, which is returning information about the executed task.
When retrieving the information returned by the submit() method, note the following:
submit() returns Future object. In order to retrieve the information about the task, we need to retrieve the information from the Future object, using get() method. Two are available:
V get()V get(long timeout, TimeUnit unit)Future.isDone() method to make sure the task completed (note that this method returns true also, if the task threw an exception or was cancelled). Callable object. As mentioned above, there are two submit() methods, one accepting a Runnable and one a Callable. Both are functional interfaces, with the key difference:
Runnable - it's run() method, accepts no value and returns on value, it cannot throw an exceptionCallable - it's call() method returns a value and can throw an exceptionCalling get() on a Future object, will return the same return type as defined by a call() method, or null if Runnable object was submitted (method run() returns no value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With