Android的承诺?

问题描述 投票:21回答:4

你如何面对Android中的嵌套回调?例如,在我的应用程序中,我使用Locations API,然后,当我有当前的lat-lng时,我向我的服务器发出HTTP请求。在这种情况下,我有两个嵌套的回调。它没有那么糟糕,但如果我有三个或更多?我已经读过它in this question但我想知道是否有像Promises for Android这样的东西。

我发现的只有this。有人对这个问题了解得更多吗?

android promise
4个回答
21
投票

作为Java语言的一部分,已经有类似的东西了,并且得到了Android的支持:java.util.concurrent.Future。也许它足以满足您的需求。

顺便说一下,Android尚未支持的Java 8有一个名为CompletableFuture的变体,它更接近Promise。


5
投票

这篇很老的帖子,但是,我想在这里分享我的问题和解决方案。

我有类似的问题,我需要在登录我的应用程序时一个接一个地执行4个网络任务,最后当所有请求都成功打开应用程序的登陆屏幕时。最初我使用嵌套回调,但现在我发现了一个新的android-Promise库https://github.com/crawlinknetworks/android-promise它解决了我的问题。它非常简单易用。

Following: How it is working?

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 

1
投票

RxJava可能是android支持和记录最多的解决方案。 Android版:https://github.com/ReactiveX/RxAndroid


0
投票

扔进我的帽子:

https://github.com/VicV/Promises

多年前写的,从那以后一直在使用它。

非常直接的承诺库。

© www.soinside.com 2019 - 2024. All rights reserved.