As of 2020, android has support for CompletableFuture, Java's answer to Javascript promises:
https://developer.android.com/reference/java/util/concurrent/CompletableFuture
If that is not possible for your app's android api level, then see https://github.com/retrostreams/android-retrofuture .
Example:
CompletableFuture.supplyAsync(()->{
String result = somebackgroundFunction();
return result;
}).thenAcceptAsync(theResult->{
//process the result
}).exceptionallyCompose(error->{
///process the error
return CompletableFuture.failedFuture(error);
});
To handle the result and update the UI, you need to specify main thread executor:
CompletableFuture.supplyAsync(()->{
String result = somebackgroundFunction();
return result;
}).thenAcceptAsync(theResult->{
//process the result
}, ContextCompat.getMainExecutor(context))
.exceptionallyComposeAsync(error->{
///process the error
return CompletableFuture.failedFuture(error);
}, ContextCompat.getMainExecutor(context));