Promises for Android?-ThrowExceptions

Exception or error:

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?

How to solve:

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.

###

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 

###

RxJava is probably the most supported and documented solution for android.
Android version: https://github.com/ReactiveX/RxAndroid

###

Tossing in my hat as well:

https://github.com/VicV/Promises

Wrote this years ago and have been using it ever since.

Very straightforward promise library.

Leave a Reply

Your email address will not be published. Required fields are marked *