dimsuz
01/13/2022, 11:36 AMdrop(1)
makes subscriber loose first emitted item:
val flow = MutableSharedFlow<Int>(replay = 1)
fun get(replayLast: Boolean): Flow<Int> = flow.drop(1) // naive impl
launch { get(replayLast = false).collect { println(it} } } // doesn't receive 1
launch { delay(1000); flow.emit(1) }
Is having two separate flows: one with replay and one witout - the only option?bezrukov
01/13/2022, 1:31 PMflow.replayCache
for this, but most likely it won't 100% robust
fun get(replayLast: Boolean): Flow<Int> = flow {
flow.drop(flow.replayCache?.size ?: 0).collect {
emit(it)
}
}
The problem is that it's unclear what to do with items emitted between flow.replayCache
and .collect
callsdimsuz
01/13/2022, 1:58 PMfun get(replayLast) = flow.drop(if (replayLast) 0 else flow.replayCache.size))
bezrukov
01/13/2022, 2:51 PMdimsuz
01/13/2022, 3:45 PMbezrukov
01/13/2022, 8:40 PM// Nothing were emitted to `flow` yet
val cold = get(replayLatest = false) // you made a cold flow with drop(0)
flow.emit(1)
cold.collect { } // you will receive 1
dimsuz
01/14/2022, 10:33 AM