Java语言已经有与之相似的东西,而且Android也支持: java.util.concurrent.Future。或许这已经足够满足您的需求。
顺便说一下,Java 8还有一个叫做CompletableFuture的变体,更接近Promise,但Android还不支持。
CompletableFuture
。请查看:https://github.com/retrostreams/android-retrofuture - rickchristie截至2020年,Android已支持CompletableFuture,它是Java对JavaScript Promise的回应: https://developer.android.com/reference/java/util/concurrent/CompletableFuture
如果你的应用程序的Android API级别不支持该特性,请参见https://github.com/retrostreams/android-retrofuture。
示例:
CompletableFuture.supplyAsync(()->{
String result = somebackgroundFunction();
return result;
}).thenAcceptAsync(theResult->{
//process the result
}).exceptionallyCompose(error->{
///process the error
return CompletableFuture.failedFuture(error);
});
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));
doSomeTask(int someValue, String extra)
.then(res -> doSecondTask((MyObject) res)) // res is result form doSomeTask()
.then(res -> doThirdTask((OtherObject) res))) // res is result form doThirdTask()
.then(res -> doFourthTask((int) res))) // res is result form doThirdTask()
.then(res -> doFivthTask())
.then(res -> {
// Consume result of the previous function
return true; // done
})
.error(err -> handleError()); // Incase of any p.reject()
// all from above function error will be available here