你如何面对Android中的嵌套回调?例如,在我的应用程序中,我使用Locations API,然后,当我有当前的lat-lng时,我向我的服务器发出HTTP请求。在这种情况下,我有两个嵌套的回调。它没有那么糟糕,但如果我有三个或更多?我已经读过它了in this question,但我想知道是否有像Promises for Android这样的东西。
我发现的只有this。有人对这个问题有更多了解吗?
答案 0 :(得分:20)
作为Java语言的一部分,已经有类似的东西了,并且得到了Android的支持:java.util.concurrent.Future。也许它足以满足您的需求。
顺便说一下,Android 8尚未支持的Java 8 ,有一个名为CompletableFuture的变体,它更接近Promise。
答案 1 :(得分:5)
这篇很老的帖子,但是,我想在这里分享我的问题和解决方案。
我有类似的问题,我需要在登录我的应用程序时一个接一个地执行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
答案 2 :(得分:5)
截至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);
});
要处理结果并更新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));
答案 3 :(得分:1)
RxJava可能是Android支持和记录最多的解决方案。 Android版:https://github.com/ReactiveX/RxAndroid
答案 4 :(得分:0)