Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple loop calls with coroutines

I need to make several calls in parallel and only send the result when everything is successful with coroutines

I want to call several pages at once. Because the API has 4 pages and I want to bring the result all at once.

I managed to do it manually like this:

private fun fetchList() {
    viewModelScope.launch {
        val item1 = async { repository.getList(1)!! }
        val item2 = async { repository.getList(2)!! }
        val item3 = async { repository.getList(3)!! }
        val item4 = async { repository.getList(4)!! }

        launch {
            mutableLiveDataList.success(item1.await() + item2.await() + item3.await() + item4.await())
        }
    }
}

But when I try to loop it, it just brings up one of the pages.

Api:

@GET("cards")
suspend fun getListCards(@Query("set") set: String, @Query("page") page: Int): CardsResponse
like image 435
OliverDamon Avatar asked Sep 16 '25 17:09

OliverDamon


1 Answers

I did as @curioustechizen said and it worked.

Here's an example of how it looks:

private fun fetchList() {
    viewModelScope.launch {

        val listPageNumbers = arrayListOf<Int>()
        (1..4).forEach { listPageNumbers.add(it) }

        listPageNumbers.map {
            delay(1000)
            async {
                mutableLiveDataList.success(repository.getListCards(it)!!)
            }
        }.awaitAll()
    }
}
like image 116
OliverDamon Avatar answered Sep 19 '25 06:09

OliverDamon