svenjacobs
01/20/2020, 7:36 AMFlow
that achieves the following: If the Flow has not produced at least one value in a given timeframe (x miliseconds), produce a default value followed by any values the Flow might produce afterwards. In contrast to a solution with debounce
however, if the Flow has produced a value before the timeframe, the default value will just be ignored and the value will be emitted immediatly.delayedDefault
😉fun <T> Flow<T>.delayedDefault(
defaultAfter: Long,
defaultValue: () -> T
): Flow<T> =
channelFlow {
val job = launch {
delay(defaultAfter)
offer(defaultValue())
}
collect {
job.cancel()
offer(it)
}
}
elizarov
01/20/2020, 9:45 AMsend(defaultValue())
just in case somebody does delayedDefault(…).buffer(0)
.svenjacobs
01/20/2020, 9:45 AMelizarov
01/20/2020, 9:47 AMjob.cancel()
after collect, so that it does not wait in the corner case of empty flow (flowOf().delayedDefault(…)
)svenjacobs
01/20/2020, 9:47 AMelizarov
01/20/2020, 9:47 AMsvenjacobs
01/20/2020, 9:48 AMsend()
inside collect
?elizarov
01/20/2020, 9:48 AMsvenjacobs
01/20/2020, 9:49 AMJob
will do nothing, right? No exception will be thrown?elizarov
01/20/2020, 9:50 AM