-
Notifications
You must be signed in to change notification settings - Fork 23
Non Cancellable job
Devrath edited this page Jan 14, 2024
·
4 revisions
- Sometimes say when we have launched multiple co-routines in scope and say some are completed and some are not completed
- Now the user invokes cancel of root scope.
- In this scenario, We want the complete execution of all co-routines in the root scope or none should be executed in the root scope, In such scenarios, We can use a
non-cancellable
job.
withContext(NonCancellable){
...
}
class NonCancellableDemoVm @Inject constructor( ) : ViewModel() {
private var job: Job? = null
fun startWithTreadSleep() {
// Start a coroutine
job = CoroutineScope(Dispatchers.Default ).launch {
coRoutineOne(1)
coRoutineOne(2)
}
}
private suspend fun coRoutineOne(coroutineNo: Int) {
withContext(NonCancellable){
try {
repeat(10) { index ->
//coroutineContext.ensureActive()
// Simulate some work
Thread.sleep(500)
// Check if the coroutine has been canceled
if (!kotlin.coroutines.coroutineContext.isActive) {
println("Coroutine-No:$coroutineNo canceled at index $index")
}else{
// Continue with the main logic
println("Coroutine-No:$coroutineNo Working at index $index")
}
}
// Additional logic after the loop
println("Coroutine-No:$coroutineNo completed")
}
catch (e: CancellationException) {
// Handle cancellation-specific tasks
println("Coroutine-No:$coroutineNo canceled")
}
}
}
fun cancel(){
job?.cancel()
}
}