Kotlin: would a coroutine job be cleaned up automatically when complete?

113 Views Asked by At

Basically what the title says. The only additional question is that if the job is not cleaned up, would those jobs be additional overhead if we keep reusing the same parent scope to create new coroutines? Thanks

additional info: I tried something like the following

suspend fun main() = supervisorScope {
    launch {
        println("inner ${[email protected]()}") //inner 1
    }
    delay(1000)
    println("outer ${[email protected]()}") //outer 0
}

So at least from here it looks like the parent scope don't need to keep track of the finished children.

1

There are 1 best solutions below

0
ryankuck On

Yes if you want to stop a coroutine from running you can do so like this:

job = launch {
    // your code
}

button.setOnClickListener() {
    job?.cancel()
}

https://kotlinlang.org/docs/cancellation-and-timeouts.html#cancellation-is-cooperative

This is basically needed if you have a loop that you want to run for a while and then stop externally.