Skip to content

Canceling the parent and child job

Devrath edited this page Aug 28, 2022 · 8 revisions

Happy scenario: Completing a job for execution

class MainActivity : AppCompatActivity() {

    val parentScope = CoroutineScope(Job() + Dispatchers.Default)

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

        Log.d("hello", "Starting point")

        val job1 = parentScope.launch {
            Log.d("hello", "Starting JOB-1")
            delay(2000)
            Log.d("hello", "Ending JOB-1")
        }.invokeOnCompletion {
            if(it is CancellationException){
                Log.d("hello", "Canceled JOB-1")
            }else{
                Log.d("hello", "Completed JOB-1")
            }
        }

    }
}

Output

2022-08-28 21:36:07.783 15604-15604/com.droid.test D/hello: Starting point
2022-08-28 21:36:07.817 15604-15643/com.droid.test D/hello: Starting JOB-1
2022-08-28 21:36:09.831 15604-15643/com.droid.test D/hello: Ending JOB-1
2022-08-28 21:36:09.832 15604-15643/com.droid.test D/hello: Completed JOB-1

Cancelling a job

class MainActivity : AppCompatActivity() {

    val parentScope = CoroutineScope(Job() + Dispatchers.Default)

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

        Log.d("hello", "Starting point")

        val job1 = parentScope.launch {
            Log.d("hello", "Starting JOB-1")
            delay(2000)
            cancel("Canceling the co-routine")
            delay(2000)
            Log.d("hello", "Ending JOB-1")
        }.invokeOnCompletion {
            if(it is CancellationException){
                Log.d("hello", "Canceled JOB-1: ${it.message}")
            }else{
                Log.d("hello", "Completed JOB-1")
            }
        }

    }
}

Output

2022-08-28 21:39:58.005 15744-15744/com.droid.test D/hello: Starting point
2022-08-28 21:39:58.024 15744-15778/com.droid.test D/hello: Starting JOB-1
2022-08-28 21:40:00.033 15744-15778/com.droid.test D/hello: Canceled JOB-1: Canceling the co-routine

Clone this wiki locally