'How to do API call in for loop in android?
How we can perform same API call in for loop of array list of object :
private var emergencyContacts: ArrayList<Contact> = ArrayList()
emergencyContacts.forEach
{
contactsViewModel.deleteEmergencyContactsAPI(it.id, it.id2)
}
fun deleteEmergencyContactsAPI(patientID: String, contactId: Int) {
_deleteEmergencyContactsLiveData.postValue(Resource.loading())
repository.deleteEmergencyContact(patientID, contactId)
.subscribeOn(Schedulers.computation())
.subscribeWith(DeleteEmergencyContactsResponse(_deleteEmergencyContactsLiveData))
}
inner class DeleteEmergencyContactsResponse(liveData: MutableLiveData<Resource<Status>>) :
ResponseSingleObserverWrapper<Status, Status>(
compositeDisposable,
liveData
) {
override fun onSuccess(t: Status) {
_deleteEmergencyContactsLiveData.postValue(Resource.success(t))
}
override fun onError(e: Throwable) {
_deleteEmergencyContactsLiveData.postValue(Resource.error(e.message ?: ""))
}
}
I want to perform UI execution after all API calls and it will not affect the screen performance.
I have tried with Zip operator , parallel network API calls but it not working nicely as API calls count is not static.
Any hint or help will be appreciated. Thank you
Solution 1:[1]
So, for calls that require time to execute, you run them on a separate thread.
So, for that, you use Coroutines
now, if you want to execute something on a main thread from a seperate thread, Coroutines can do that too. here's an example.
CoroutineScope(Dispatchers.IO).launch {
StuffYouWantOnADifferentThread()
CoroutineScope(Dispatchers.Main).launch {
StuffYouWantOnTheMainThread()
}
}
What happens here is, The IO Coroutine launches the StuffYouWantOnADifferentThread() on a background thread. Then, after that is executed, the Main Coroutine executes the StuffYouWantOnTheMainThread() on the main thread.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vaishnav Kanhirathingal |
