Android的承诺?

Android的承诺?,android,promise,Android,Promise,您如何面对Android中的嵌套回调?例如,在我的应用程序中,我使用Locations API,然后,当我有当前的lat lng时,我向我的服务器发出HTTP请求。在这种情况下,我有两个嵌套回调。没那么糟,但如果我有三个或更多呢?我已经读过了,但我想知道是否有类似Android的承诺 我所发现的就是。有人更了解这个主题吗?Java语言中已经提供了一些类似的东西,Android支持这些东西:。也许它足够满足你的需要 顺便说一句,Android还不支持的Java8有一个变体,叫做,更接近于承诺。这篇

您如何面对Android中的嵌套回调?例如,在我的应用程序中,我使用Locations API,然后,当我有当前的lat lng时,我向我的服务器发出HTTP请求。在这种情况下,我有两个嵌套回调。没那么糟,但如果我有三个或更多呢?我已经读过了,但我想知道是否有类似Android的承诺


我所发现的就是。有人更了解这个主题吗?

Java语言中已经提供了一些类似的东西,Android支持这些东西:。也许它足够满足你的需要


顺便说一句,Android还不支持的Java8有一个变体,叫做,更接近于承诺。

这篇非常古老的文章,但是,我想在这里分享我的问题和解决方案

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

以下内容:它是如何工作的?
截至2020年,android已经支持CompletableFuture,Java对Javascript的回应承诺:

如果您的应用程序的android api级别不可能做到这一点,请参阅

例如:

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));

当然可以,但是请注意,如果没有Java8函数接口语法,这看起来真的很难看。承诺是一个取自函数式编程的概念,即。谢谢。现在,这在实际开发中使用了吗?我看过iosched和其他Android应用程序的源代码,但我从来没有听说过承诺。是的,Future被大量使用。下面是一个可能有用的教程:添加到Android 7(API级别24)中,Java 8部分受支持(不是Jack)“Java语言中已经有一些非常类似的东西,并且由Android支持:Java.util.concurrent.Future。”)未来真的与承诺不太相似。虽然承诺是基于回调的,但未来通常是同步等待的。如何让它工作呢?我将Promise.java放在app/src中,什么都没有发生!像个JS!欢迎链接到某个解决方案,但请确保您的答案在没有它的情况下是有用的:这样您的其他用户就会知道它是什么以及为什么存在,然后引用您链接到的页面的最相关部分,以防目标页面不可用。
        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));