cyb*_*sam 21
作为Java语言的一部分,已经有类似的东西了,并且得到了Android的支持:java.util.concurrent.Future.也许它足以满足您的需求.
顺便说一下,Android尚未支持的 Java 8 有一个名为CompletableFuture的变体,它更接近Promise.
截至 2020 年,android 已支持 CompletableFuture,Java 对 Javascript 承诺的回答: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);
});
Run Code Online (Sandbox Code Playgroud)
要处理结果并更新 UI,您需要指定主线程执行器:
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));
Run Code Online (Sandbox Code Playgroud)
这个非常老的帖子,但是,我想在这里分享我的问题和解决方案。
我有类似的问题,登录到我的应用程序时,我需要一次又一次执行4个网络任务,最后,当所有请求成功打开应用程序的登录屏幕时,我将依次执行这四个任务。最初我使用嵌套回调,但是现在我发现了一个新的android-promise库https://github.com/crawlinknetworks/android-promise,它解决了我的问题。它非常容易使用。
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
Run Code Online (Sandbox Code Playgroud)