Stopping jobs in onCleared() of ViewModel after activity finish shows the JobCancellationException: Job is being canceled and keeps app freeze crash:
What would be the right way to cancel all kotlin coroutines pending jobs from ViewModel's onCleared() in Android
My code inside viewModel:
private val job = SupervisorJob()
private val uiScope = CoroutineScope(Dispatchers.Main + job)
uiScope.launch {
try {
repeat(152212000001) { it ->
try {
Log.d("Timer : ", it)
delay(1000)
} catch (e: Exception) {
e.printStackTrace()
}
}
} catch (e: CancellationException) {
e.printStackTrace()
}
}
Inside ViewModel:
override fun onCleared() {
job.cancel()
super.onCleared()
}