简体   繁体   中英

Kotlin - How to wait for multiple API calls to finish and update UI?

I'm new to kotlin coroutines. I've been trying to run multiple API calls in parallel and then when all the calls are done update my UI and dismiss the loader, but with no success. This is my code

private fun getScoreForType() {
    val job = CoroutineScope(Dispatchers.IO).launch {
        types.forEach { type ->
            getScore(type)
        }
    }

    runBlocking {
        job.join()
        // do some ui work
        dismissLoader()
    }
}


private fun getScore(type: String) {
    val call = MyApi.getScores(type)

    call.enqueue(object : Callback<Score> {
        override fun onResponse(call: Call<Score>, response: Response<Score>) {
            setScore(response)
        }

        override fun onFailure(call: Call<Score>, t: Throwable) {
        }

    })
}

I've also tried using async and awaitAll but couldn't make it work either. The loader is always dismissed before all the calls are done. Any help on how I could make this work would be much appreciated

Use Flow and collectData it will works as LiveData.

For example:

val myIntFlow = MutableStateFlow(-1)

Try something like;

in ViewModelMethods

private fun getScoreForType() {
It goes first:
    CoroutineScope(Dispatchers.IO).launch {
        types.forEach { type ->
            getScore(type)
        }
 // it means to change value of flow

myIntFlow.value = 1
    }
    // Now collect data in fragment to change UI

}
// in fragment like:
CoroutineScope(Dispatchers.Main).launch {
// flow will be triggered, on every changed value
viewModel.myIntFlow.collect {
viewModel.methodFromViewModelToChangeUI()
dissmisloader()
myIntFlow.value = -1
}
}


// try the same here as you wish

private fun getScore(type: String) {
    val call = MyApi.getScores(type)

    call.enqueue(object : Callback<Score> {
        override fun onResponse(call: Call<Score>, response: Response<Score>) {
            setScore(response)
        }

        override fun onFailure(call: Call<Score>, t: Throwable) {
        }

    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM