Channels of Channels

With coroutines, you’re able to use select to wait on a number of channels simultaneously. Is it possible to update the list of channels being waited on after the initial execution of the select block? Basically, I’d like to be able to pass a channel through another channel, and then select on that.

Something roughly like this:

select<Unit> {
    channel.onReceive { obj ->
        obj.onReceive { inner ->
            // do stuff
        }
    }
}

However, this doesn’t really seem to work – even when something is sent to the “inner” channel, it doesn’t ever get consumed. Is there any way to make this work?

You’ll have to wake up your original select and then restart with a new list of clauses. Adding a new clause to a waiting select expression is not currently supported via its public API, even though its internal implementation architecture kind of supports it (you can register at any time). You are welcome to file a feature request to kotlinx.coroutines project (don’t forget to add some more motivation) and/or contribution the corresponding implementation via pull request.

1 Like

Sounds good. Thanks Roman.