安卓版的承诺?

23
如何在Android中处理嵌套回调?例如,在我的应用中,我使用位置API,然后当我有当前的纬度和经度时,我会向我的服务器发送一个HTTP请求。在这种情况下,我有两个嵌套的回调。这还不算太糟糕,但如果我有三个或更多呢?我已经阅读了关于这个问题的链接,但我想知道是否有类似于Android的Promise的东西。
我找到的唯一的链接是这个。有人对这个主题了解更多吗?

5
当然,但需要注意的是,如果没有Java 8的函数接口语法,这看起来会非常丑陋。Promises是从函数式编程中借鉴而来的概念。 - Benjamin Gruenbaum
3个回答

24

Java语言已经有与之相似的东西,而且Android也支持: java.util.concurrent.Future。或许这已经足够满足您的需求。

顺便说一下,Java 8还有一个叫做CompletableFuture的变体,更接近Promise,但Android还不支持。


谢谢。现在,这个在实际开发中使用吗?我看过iosched和其他Android应用程序的源代码,但从未听说过Promises。 - Marcos
是的,Future被广泛使用。这里有一个可能会有帮助的教程:http://java.dzone.com/articles/javautilconcurrentfuture - cybersam
6
在Android 7(API级别24)中添加了CompletableFuture。 - Stefan Frye
Java 8部分支持(不包括Jack)https://developer.android.com/studio/write/java8-support.html - user221256
1
"Java 语言和 Android 支持的 java.util.concurrent.Future 已经提供了类似的功能。但是 Future 和 Promise 还是有很大的不同,Promise 是基于回调的,而 Future 通常是同步等待的。" - MarkusM
请记住,如果您想支持旧设备,可以使用专门为Android制作的后移CompletableFuture。请查看:https://github.com/retrostreams/android-retrofuture - rickchristie

7

截至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);
        });

为了处理结果并更新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));

欢迎提供解决方案的链接,但请确保您的答案即使没有链接也是有用的:在链接周围添加上下文,以便其他用户知道它是什么以及为什么存在,然后引用您链接的页面中最相关的部分,以防目标页面不可用。仅仅是一个链接的答案可能会被删除。 - dippas

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 

你怎么让它工作?我把Promise.java放在app/src中,但什么也没有发生。 - Cesar Vega
太棒了!就像JS一样! - HerberthObregon
从 Github 上看,您似乎是这个作品的原始作者。正如“问题”页面中其他人所指出的那样,许可证在第二次提交中从 Apache 更改为更加限制性的许可证(同时还修复/添加了一些东西)。这个限制性许可证是一个错误吗,还是不再免费使用? - chrisbtoo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接