https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tristan Caron

03/27/2018, 3:01 PM
Hello, How I can cancel a consumeEach from a channel?
l

louiscad

03/27/2018, 3:10 PM
@Tristan Caron By using
return@consumeEach
t

Tristan Caron

03/27/2018, 3:16 PM
I mean, to prevent it to consume more
u

uhe

03/27/2018, 3:19 PM
close the channel (by calling
close
or cancelling the producer) or cancel the consuming coroutine
depends on what you actually wanna do
t

Tristan Caron

03/27/2018, 3:27 PM
Actually, it's a ConflatedBroadcastChannel, I want to avoid to close it. Canceling the coroutine doesn't seem to work
Copy code
launch(job) { // ... consumer }
job.cancel()
e

elizarov

03/27/2018, 8:07 PM
Can you give, please, a self-contained example of code that does not work when you cancel a job?
t

Tristan Caron

03/28/2018, 9:01 AM
It's working, my bad. I was not cancelling the correct job. This works
Copy code
fun main(args: Array<String>) = runBlocking {
    val channel = ConflatedBroadcastChannel<String>()

    val job = launch {
        channel.consumeEach {
            println(it)
        }
    }

    channel.send("This should be printed")

    delay(1000)

    println("Cancelling job")
    job.cancel()

    delay(1000)

    channel.send("This should not be printed")

    delay(1000)

    println("Done")
}
2 Views