Promise/Deferred
A deferred object allows you to separate the following two concerns:
- Work on the background
- Doing something with the result
Using the api should be easy and straight forward without too much boiler plate. To execute code in the background:
Promise<String> promise = Function.execute(new Callable<String>() {
@Override
public String call() throws Exception {
// This method will run on a background thread
return "Hello world!";
}
});
Or in Android studio it will be readable like this:
Promise<String> promise = execute(() -> {return "Hello world!";});
This promise can be used to add tasks that needs to be executed on success or on error. An example:
promise.thenOnMainThread(new Task<String>() {
@Override
public void run(String message) {
Toast.makeText(getContext(), message, LENGTH_LONG);
}
})
.onErrorOnMainThread(new Task<Throwable>() {
@Override
public void run(Throwable data) {
Toast.makeText(getContext(), "Oops!", LENGTH_LONG);
}
});
And in Android Studio it will look like:
promise.thenOnMainThread(() -> {Toast.makeText(getContext(), message, LENGTH_LONG);})
.onErrorOnMainThread(() -> {Toast.makeText(getContext(), "Oops!", LENGTH_LONG);});
You don't have to worry about the promise already been resolved or not. If the promise is not resolved, the task will be scheduled to be executed when the promise is resolved. The task will be executed immediately if the promise is already resolved. The order of the tasks is respected for tasks that are scheduled on the same thread.
Threads
You can schedule tasks to be executed on different threads:
- then(Task), onError(Task): The task will be executed on the same thread that resolved the promise
- thenOnMainThread(Task), onErrorOnMainThread(Task): The task will be executed on the main thread. On this thread the UI can be updated.
- thenOnBackgroundThread(Task), onErrorOnBackgroundThread(Task): The task will not be executed on the main thread. If the current thread is the main thread, the task will be executed on a background thread.
- thenAsync(Task), onErrorAsync(Task): The task will always be executed on a new thread.