Skip to content

Coroutines: Wait for coroutine to finish

Devrath edited this page Dec 30, 2023 · 1 revision

Observation

  • Here observe the output, In the parent co-routine, which is a view model scope, We have launched a new coroutine scope.
  • But even though the inner co-routine is suspended since we have used join(), It will wait meaning the no-4 is executed after the inner scope.

Code

    fun waitForCoRoutineToFinish() {
        //println("Before the view model scope")
        viewModelScope.launch {
            println("Before the coroutine scope") // - 1
            CoroutineScope(EmptyCoroutineContext).launch {
                println("Before the delay") // - 2
                delay(1000)
                println("After the delay") // - 3
            }.join()
            println("After the coroutine scope") // - 4
        }
        //println("After the view model scope")
    }

Output

Before the coroutine scope
Before the delay
After the delay
After the coroutine scope
Clone this wiki locally