Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android equivalent of iOS GCD dispatch_group API

I come from an iOS background and I'm new to Android.

Is there an efficient and fast way to make the same network API call but with different parameters each time where the parameters are stored in an array. I would only want to return when all the network API calls have completed, but I don't want any of the api calls in the loop to block other api calls in the loop.

I basically want the equivalent of this Swift code. Basically the function below won't return until all network calls getData has either succeeded or failed. How would I accomplish the same thing below in Android?

func getDataForParameters(array: NSArray) {
    let group = dispatch_group_create()
    for (var i = 0; i < array!.count(); i++) {
        let param = array![i]
        dispatch_group_enter(group)

        getData(param, success: {
            () in
            dispatch_group_leave(group)

            }, failure: {
                () in
                dispatch_group_leave(group)
        })
    }
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
}
like image 693
user299648 Avatar asked Aug 03 '16 07:08

user299648


2 Answers

You have many ways to achieve this.

  1. You can use Thread.join() in case you are using threads
  2. you can use 3rd party libraries like RxJava.
  3. you can write your own event dispatcher here is an ugly example
  4. This answer also covers your question Callable and Future
like image 112
Ercan Avatar answered Oct 04 '22 05:10

Ercan


If the network calls in the loop shouldn't block other network call then you should make the network calls asynchronously.

You can use google's volley network library to make the network calls and they execute asynchronously. Follow the below link for volley

https://developer.android.com/training/volley/index.html.

if you can implement a counter which increments on either success or failure call back you can use that variable to determine whento return back to your calling method.

Since the network calls are being made asynchronously you need to write a callback interface which should be triggered once your counter condition is met so that it will send a callback to the called method. you can find lot of examples on how use callback mechanism in Android. Callback functions are like Delegate functions in IOS.

I Hope this helps.

like image 27
Avinash4551 Avatar answered Oct 04 '22 04:10

Avinash4551