- 
                Notifications
    
You must be signed in to change notification settings  - Fork 24
 
Using IsActive for co‐operative cancellation
        Devrath edited this page Jan 14, 2024 
        ·
        2 revisions
      
    
- Co-routine cancellation is tricky because it needs to be cooperative.
 - There must be some cooperation between the code that canceling and the code that is being canceled.
 - Also the process must be clean and proper.
 
- It provides the ability to check at any point of execution whether the coroutine is canceled by the job handle.
 - When they are canceled immediately we can check in the code flow if the co-routine is already canceled and perform a clean up operation or anything needed.
 
code
class IsActiveDemoVm @Inject constructor( ) : ViewModel() {
    private var job: Job? = null
    fun startWithTreadSleep() {
        // Start a coroutine
        job = CoroutineScope(Dispatchers.Default).launch {
            try {
                repeat(5000) { index ->
                    // Simulate some work
                    Thread.sleep(500)
                    // Check if the coroutine has been canceled
                    if (!isActive) {
                        println("Coroutine canceled at index $index")
                        return@launch
                    }
                    // Continue with the main logic
                    println("Working at index $index")
                }
                // Additional logic after the loop
                println("Coroutine completed")
            } catch (e: CancellationException) {
                // Handle cancellation-specific tasks
                println("Coroutine canceled")
            }
        }
    }
    fun cancel(){
        job?.cancel()
    }
}Output
Working at index 0
Working at index 1
Working at index 2
Working at index 3
Coroutine canceled at index 4