3

I want to call a request to an API in a loop and observe the result for each api requests. The problem is that I think some result are got lost. How can I handle this? I want to handle this using flow or stateflow. Is it better to wait to get result from a request then proceed to another number in the loop? How? Or is there a coroutines function that pauses a loop till the result is observed?

lifecycleScope.launchWhenCreated {

        for (i in 1..100) {
            viewModel.apiRequest(i)
        }
}
lifecycleScope.launchWhenCreated {

       viewModel.resultStateFLow.observe {
  // update ui or ..
    }
}

Mehran Jalili
  • 585
  • 7
  • 18
  • It is not good practice to send this many requests at once, maybe you have to re-consider the realization of your feature. In this scenario, the problem is your requests may not return results in the same order as they were sent. If you need responses to be in proper order you have to wait for each response. – Azim Salimov Jul 27 '21 at 10:48
  • So I should just call the next request in the observer? Is there a better way to do this? – Mehran Jalili Jul 28 '21 at 12:52

0 Answers0