Co-routine flow wrapper

from the CommonsWare Community archives

At April 6, 2021, 9:08pm, Jan asked:

I have read your 0.3 co-routine book.
In this book you say, “There are two extension functions for ReceiveChannel that wrap it in a Flow :
receiveAsFlow() and consumeAsFlow()”

You don’t give an example. Is the below code how you would wrap it:
val notifyChannel: ReceiveChannel
val notifyFlow: ReceiveChannel.receiveAsFlow()

I have an extension operator on ReceiveChannel. Can I move that extension operator to Flow?

Further regarding operators, you say:
"Channel ,
and its various subtypes like BroadcastChannel , has a lot of extension
functions that serve as operators, much like the ones we have for Flow . However,
most, if not all, are marked as deprecated. In general, the expectation now is that
you will do any “heavy lifting” using a Flow , perhaps one adapted from a Channel .

To “adapt” a BroadcastChannel or a regular channel, do I use a wrapper like for ReceiveChannel
or do I have to rewrite that code?

private val characteristicChangedChannel =
private val readDescChannel = Channel<GattResponse>()

At April 6, 2021, 9:42pm, mmurphy replied:

No, it would be more like:

val notifyChannel: ReceiveChannel = TODO("you need to initialize this!")
val notifyFlow = notifyChannel.receiveAsFlow()

Sorry, but since I do not know what the extension function does, I cannot tell you if the same code that works with a ReceiveChannel will work with a Flow.

ReceiveChannel is an interface. Channel extends ReceiveChannel. So, you can wrap a Channel in a Flow via receiveAsFlow() or consumeAsFlow().

BroadcastChannel has an asFlow() extension function.