Skip to content

Coroutines: Sequential coroutines execution

Devrath edited this page Dec 30, 2023 · 1 revision

Observation

  • Here observe that the co-routine is executed one after another sequentially.
  • We have used join() to achieve this

Code

        viewModelScope.launch {
            println("JOB-1: Before the coroutine scope")
            CoroutineScope(EmptyCoroutineContext).launch {
                println("JOB-1: ----> Before the delay")
                delay(1000)
                println("JOB-1: ----> After the delay")
            }.join()
            println("JOB-1: After the coroutine scope")
            println("---------------------------------")
            println("JOB-2: Before the coroutine scope")
            CoroutineScope(EmptyCoroutineContext).launch {
                println("JOB-2: ----> Before the delay")
                delay(1000)
                println("JOB-2: ----> After the delay")
            }.join()
            println("JOB-2: After the coroutine scope")
        }

Output

JOB-1: Before the coroutine scope
JOB-1: ----> Before the delay
JOB-1: ----> After the delay
JOB-1: After the coroutine scope
---------------------------------
JOB-2: Before the coroutine scope
JOB-2: ----> Before the delay
JOB-2: ----> After the delay
JOB-2: After the coroutine scope
Clone this wiki locally