Frank Bastin
Frank Bastin

Reputation: 13

Cancel current co routine kotlin

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

Answers (1)

Eugene Popovich
Eugene Popovich

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

Related Questions