Reputation: 13
How do i cancel the current co routine if the current coroutine is active ? Here is the code
fun coRoutine2(interval: Long) {
val coroutineScope = CoroutineScope(Dispatchers.IO)
if (coroutineScope.isActive) {
coroutineScope.cancel()
} else {
coroutineScope.launch {
for (i in 1..progressBar.max) {
delay(interval)
progressBar.progress = i
println(i)
}
}
}
}
Upvotes: 1
Views: 43
Reputation: 3483
If you want to cancel couroutine you should cancel the Job
object returned when you call launch
method
val job = coroutineScope.launch {
for (i in 1..progressBar.max) {
delay(interval)
progressBar.progress = i
println(i)
}
}
job.cancel()
see more examples in official documentation
Upvotes: 1