Skip to content

Closing SubscriptionReceiveChannel inside consumeEach throws NPE #97

Closed
@patrickjuchli

Description

@patrickjuchli

I have an NPE when closing a SubscriptionReceiveChannel of a BroadcastChannel inside a consumeEach block. For example:

fun main(args: Array<String>) = runBlocking<Unit> {
    val channel = BroadcastChannel<Int>(1)
    launch(CommonPool) {
        for (x in 1..5) {
            delay(100L)
            channel.send(x)
        }
        channel.close()
    }
    val sub = channel.openSubscription()
    sub.consumeEach {
        println(it)
        if (it == 2) {
            sub.close()
            // Adding return@consumeEach here doesn't help
        }
    }
    println("Done!")
}

consumeEach should probably check whether a channel is closed, I was surprised when I encountered this. In the meantime, this workaround helps:

for (value in sub) {
    println(value)
    if (value == 2) {
        sub.close()
        break // This is necessary
    }
}    

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions