Promises for Android?

陌路散爱 提交于 2020-06-09 16:46:13

问题


How do you face nested callbacks in Android? For example, in my app I use Locations API and then, when I have the current lat-lng, I do an HTTP request to my server. In this situation I have two nested callbacks. It's no so bad, but what If I had three or more? I've read about it in this question but I wonder if there are something like Promises for Android.

All I've found is this. Someone knows more about the subject?


回答1:


There is something pretty similar already available as part of the Java language, and supported by Android: java.util.concurrent.Future. Perhaps it is good enough for your needs.

By the way, Java 8, which Android does not yet support, has a variant called CompletableFuture that is even closer to a Promise.




回答2:


This very old post, but, I want to share my problem and solution here.

I has similar problem, I need to perform 4 network task one after another while login to my app and finally when all requests are success opening the landing screen of the app. Initially I used nested callback, but now i found a new android-Promise library https://github.com/crawlinknetworks/android-promise it solved my problem. It is very easy and simple to use.

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 



回答3:


As of 2020, android has support for CompletableFuture, Java's answer to Javascript promises: https://developer.android.com/reference/java/util/concurrent/CompletableFuture

If that is not possible for your app's android api level, then see https://github.com/retrostreams/android-retrofuture



来源:https://stackoverflow.com/questions/23164196/promises-for-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!