Android的承诺?

Enr*_*cos 23 android promise

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

我发现的就是这个.有人对这个问题了解得更多吗?

cyb*_*sam 21

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

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

  • Android 7中添加了[CompletableFuture](https://developer.android.com/reference/java/util/concurrent/CompletableFuture.html)(API级别24) (4认同)

Kid*_*ogo 6

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


PAR*_*HAN 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 
Run Code Online (Sandbox Code Playgroud)