Skip to content

Making parent co routine to wait until all the children co routines are finished

Devrath edited this page Aug 28, 2022 · 1 revision
class MainActivity : AppCompatActivity() {

    val scope = CoroutineScope(Dispatchers.Default)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d("hello","Before scope")

        runBlocking {
            val parentCoroutineJob = scope.launch {
                launch {
                    delay(2000)
                    Log.d("hello","Child co-routine-1 is done")
                }
                launch {
                    delay(1000)
                    Log.d("hello","Child co-routine-2 is done")
                }
            }
             parentCoroutineJob.join()
        }

        Log.d("hello","After scope")

    }
}

If parentCoroutineJob.join() is not commented

2022-08-28 17:26:54.022 10116-10116/com.droid.test D/hello: Before scope
2022-08-28 17:26:55.041 10116-10149/com.droid.test D/hello: Child co-routine-2 is done
2022-08-28 17:26:56.041 10116-10149/com.droid.test D/hello: Child co-routine-1 is done
2022-08-28 17:26:56.041 10116-10116/com.droid.test D/hello: After scope

If parentCoroutineJob.join() is commented

2022-08-28 17:44:13.802 10482-10482/com.droid.test D/hello: Before scope
2022-08-28 17:44:13.814 10482-10482/com.droid.test D/hello: After scope
2022-08-28 17:44:14.821 10482-10508/com.droid.test D/hello: Child co-routine-2 is done
2022-08-28 17:44:15.822 10482-10508/com.droid.test D/hello: Child co-routine-1 is done
Clone this wiki locally