Home > Software engineering >  How to do API call in for loop in android?
How to do API call in for loop in android?

Time:04-08

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 one rror(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

CodePudding user response:

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.

  • Related