OliverDamon
OliverDamon

Reputation: 417

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

Upvotes: 4

Views: 3114

Answers (1)

OliverDamon
OliverDamon

Reputation: 417

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()
    }
}

Upvotes: 3

Related Questions