What is the most idiomatic way of having a `Mutabl...
# coroutines
u
What is the most idiomatic way of having a
MutableSharedFlow
(that acts as a trigger to refresh stuff), that has a default value (so syncs get triggered right away on start)? I find manually throwing in `trigger.emit(Unit)`after everyone is subscriber a bit awkwards Unless there is an API I'm not aware of, probably the best would be to have own subclass right? Like this maybe?
Copy code
class TriggerFlow : Flow<Unit> {
    private val _trigger = MutableSharedFlow<Unit>(
        replay = 1
    )
    
    init {
        _trigger.tryEmit(Unit)
    }
    
    suspend fun trigger() {
        _trigger.emit(Unit)
    }
    
    override suspend fun collect(collector: FlowCollector<Unit>) {
        _trigger.collect(collector)
    }
}
How does this look? Is the
tryEmit
in init cool?
s
You can emit values in a (MutableShared)Flow's
onStart
callback.
u
but that's subscription local, no? i.e. I have to do it on every callsite (?)
s
createOrGetMySharedFlow().onStart { emit(Unit) }..... collect { ... }
should work, I think
This would add an onStart for each collect call
u
yea, which makes me think that populating the replay buffer would be clear, no?
s
I think so, yes. But I'd need to try/test that 😁