Hello, How I can cancel a consumeEach from a chann...
# coroutines
t
Hello, How I can cancel a consumeEach from a channel?
l
@Tristan Caron By using
return@consumeEach
t
I mean, to prevent it to consume more
u
close the channel (by calling
close
or cancelling the producer) or cancel the consuming coroutine
depends on what you actually wanna do
t
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
Can you give, please, a self-contained example of code that does not work when you cancel a job?
t
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")
}