https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

rkeazor

02/22/2020, 9:15 PM
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

Adam Powell

02/22/2020, 9:15 PM
BroadcastChannel<T>.asFlow()
?
r

rkeazor

02/22/2020, 9:17 PM
wow didn't know about this extension . is it experimental , or FlowPreview?
a

Adam Powell

02/22/2020, 9:17 PM
don't remember, but I use it all over 🙂
r

rkeazor

02/22/2020, 9:18 PM
Nicee, good to know its battle tested ! Thanks dude!
l

louiscad

02/23/2020, 1:47 AM
It's FlowPreview. I copied it to avoid sudden changes.
r

rkeazor

02/23/2020, 3:59 PM
oh i see, Flow Preview doesn't have a promise of a migration path?
b

Brendan Weinstein

02/23/2020, 5:31 PM
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

louiscad

02/24/2020, 8:03 AM
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

Brendan Weinstein

02/25/2020, 10:35 PM
I see that perspective. We are using Koin at work so folks preferred having a specific class name to avoid named injectors.