mbonnin
05/07/2021, 3:07 PMMutableSharedFlow
before emitting something ?
val mutableFlow = MutableSharedFlow<Int>()
val sharedFlow = mutableFlow.asSharedFlow()
// start listening to the sharedFlow
launch {
sharedFlow
.collect {
// by the time we start collecting, the first item is gone already
// and nothing is received
println("$it")
}
}
// emit something
mutableFlow.emit(1)
Adding a delay before emitting works but doesn't sound great and I don't see a way to enforce a before-after relationship thereTijl
05/07/2021, 3:14 PMyield()
instead of delay might do the trick, but you can also collect the .subscriptionCount
on your mutableFlow
until it is 1
mbonnin
05/07/2021, 3:18 PMcollect theThis will ultimately be called from different threads so that sounds dangerous.subscriptionCount
Tijl
05/07/2021, 3:25 PMTijl
05/07/2021, 3:25 PMmbonnin
05/07/2021, 3:27 PMmbonnin
05/07/2021, 3:28 PMmbonnin
05/07/2021, 3:28 PMTijl
05/07/2021, 3:38 PMjw
05/07/2021, 3:38 PMlaunch(start = UNDISPATCHED) { .. }
jw
05/07/2021, 3:39 PMbabel
05/07/2021, 9:29 PMreplay = 1
into MutableSharedFlow would also get you the printlnmbonnin
05/07/2021, 9:36 PMreplay = 1
doesn't work anymore if there can be n emitted items as I don't know 'n' beforehand. Overall I like the onSubscription()
solution. Looks like it was made especially for this use case