james04
james04

Reputation: 1920

How to wait for all the async to finish?

I have a list of requests that i want to do and i want to wait for all of them to finish in order to procceed. I am using kotlin coroutines with repeat and async like below.

viewModelScope.launch(Dispatchers.IO) {
            repeat(serverAccountList.size) { 
                async { 
                    createHelloRequest(it)  // suspend function
                }
            }



            withContext(Dispatchers.Main) {
                _isLoading.value = false
            }
        }

How can i join them so i can continue my code inside Main Dispatcher?

Upvotes: 2

Views: 7485

Answers (3)

Pritam Kadam
Pritam Kadam

Reputation: 2527


    val jobs = mutableListOf<Job>()

    viewModelScope.launch(Dispatchers.IO) {
        repeat(serverAccountList.size) { 
            // save all job handles to mutable variable
            jobs += async { createHelloRequest(it) }
        }

        // await on all jobs
        jobs.awaitAll()   

        withContext(Dispatchers.Main) {
            _isLoading.value = false
        }
    }

Upvotes: -1

Marko Topolnik
Marko Topolnik

Reputation: 200138

Don't use Dispatchers.IO to call suspendable (non-blocking) functions. All your code can stay on the Main dispatcher. Also, use coroutineScope to launch as many subtasks as you need and Kotlin will ensure all are complete before the coroutineScope call completes.

All put together, your code should look like this:

viewModelScope.launch {
    _isLoading.value = true
    coroutineScope {
        repeat(serverAccountList.size) {
            launch { createHelloRequest(it) }
        }
    }
    _isLoading.value = false
}

Upvotes: 2

r2rek
r2rek

Reputation: 2233

You need to call await for your async - e.g.

...

val stuff = async {...}
stuff.await()
...

Upvotes: 0

Related Questions