Dmitriy Puchkov
Dmitriy Puchkov

Reputation: 1601

Kotlin coroutines barrier: Wait for all coroutines to finish

I need to start many coroutines in a for loop and get a callback in the Main thread after all the tasks are completed.

What is the best way to do this?

//Main thread
fun foo(){
    messageRepo.getMessages().forEach {message->
       GlobalScope.launch {
            doHardWork(message)
       }
    }
   // here I need some callback to the Main thread that all work is done.
}

And there is no variant to iterate messages in CoroutineScope. The iteration must be done in the Main thread.

Upvotes: 2

Views: 1503

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8422

You can wait until all tasks will be completed with awaitAll and then execute your callback in the main thread with withContext

fun foo() {
    viewModelScope.launch {
        messageRepo.getMessages().map { message ->
            viewModelScope.async(Dispatchers.IO) {
                doHardWork(message)
            }
        }.awaitAll()
        withContext(Dispatchers.Main) {
            // here I need some callback that all work is done.
        }
    }
}

Upvotes: 4

Related Questions