Whats the best way to integrate a Broadcast Channe...
# coroutines
r
Whats the best way to integrate a Broadcast Channel and Flow together?So that you have a hot flow, that collects anything that the broadcast channel emits
a
BroadcastChannel<T>.asFlow()
?
r
wow didn't know about this extension . is it experimental , or FlowPreview?
a
don't remember, but I use it all over 🙂
r
Nicee, good to know its battle tested ! Thanks dude!
l
It's FlowPreview. I copied it to avoid sudden changes.
r
oh i see, Flow Preview doesn't have a promise of a migration path?
b
Copy code
class EventProducer(private val channel: BroadcastChannel<Event>) :
    SendChannel<Event> by channel

class EventConsumer(private val channel: BroadcastChannel<Event>) :
    Flow<Event> by channel.asFlow()
😍 1
I've also played with
Copy code
class FlowRelay<T>(capacity: Int) : Flow<T> {
    @InternalCoroutinesApi
    override suspend fun collect(collector: FlowCollector<T>) {
        flow.collect(collector)
    }

    @UseExperimental(ExperimentalCoroutinesApi::class)
    private val broadcastChannel = BroadcastChannel<T>(capacity)

    @UseExperimental(FlowPreview::class)
    private val flow: Flow<T> = broadcastChannel.asFlow()

    @UseExperimental(ExperimentalCoroutinesApi::class)
    suspend fun send(event: T) {
        broadcastChannel.send(event)
    }
}
l
The naming of the
EventConsumer
class is lying to what it actually is, plus it's pointless, you can just use
asFlow
and keep a reference to it, your binary will end up smaller, and your code simpler.
b
I see that perspective. We are using Koin at work so folks preferred having a specific class name to avoid named injectors.