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)
}
You have many ways to achieve this.
Thread.join()
in case you are using threadsCallable
and Future
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With