Skip to content

Cancelling Coroutine Vs Cancelling Coroutines children

Devrath edited this page Jan 11, 2024 · 3 revisions

🚨 Important Difference

  • Cancelling a co-routine involves stopping all the suspending functions and its children.
  • If we cancel an entire coroutine via root, You cannot restart it
    • When you try to re-start it, It will throw an exception called Job was canceled
  • If we cancel only the children, We can restart the co-routine again.
    • It will throw the exception called StandaloneCoroutine was canceled but as said above, we can restart it.

DemoCode

class CoroutineCancelSelectionVm @Inject constructor( ) : ViewModel() {

    private val rootScope =  CoroutineScope(Dispatchers.Default)

    fun start() {
        rootScope.launch {
            longRunningOperation()
        }.invokeOnCompletion {
            it?.let {
                val message = it?.message
                println("Exception thrown:-> $message")
            }?:run {
                println("Scope completed without exception")
            }
        }
    }

    fun cancelRoot(){
        rootScope.cancel()
    }

    fun cancelChildren(){
        rootScope.coroutineContext.cancelChildren()
    }

    private suspend fun longRunningOperation() = withContext(Dispatchers.Default){

        for (i in 1..30){
            println("Current count $i")
            delay(1000)
        }
    }


}
Clone this wiki locally