ursus
05/03/2021, 2:24 AMprivate fun <T> Flow<T>.onStartDebounced(initialValue: T, debounceMillis: Long): Flow<T> {
return onStart { emit(initialValue) }
.withIndex()
.debounce { if (it.index == 0) debounceMillis else 0L }
.map { it.value }
}
Works, but im a Rx guy, is there something more idiomatic / performant (so I can actually learn something)?baxter
05/03/2021, 2:43 AMMigration.kt
file for some insight on how to migrate it to Flow
.
That's normally helped some of my teammates when I work with them on getting something new as a Flow. Just remember, Single
and Maybe
are suspend
functions now.ephemient
05/03/2021, 3:03 AMfun <T> Flow<T>.onStartDebounced(
initialValue: T,
debounceMillis: Long
) = channelFlow<T> {
val job = launch {
delay(debounceMillis)
send(initialValue)
}
collect {
job.cancel()
send(it)
}
}
ursus
05/03/2021, 3:13 AMephemient
05/03/2021, 3:13 AMfun <T> Flow<T>.onStartDebounced(
initialValue: T,
debounceMillis: Long
) = flow<T> {
var hasValue = false
emitAll(
merge(
onEach { hasValue = true },
flowOf(initialValue)
.onStart { delay(debounceMillis) }
.filter { !hasValue }
)
)
}
ursus
05/03/2021, 3:16 AMephemient
05/03/2021, 3:16 AMursus
05/03/2021, 3:17 AMephemient
05/03/2021, 3:18 AMursus
05/03/2021, 3:21 AMephemient
05/03/2021, 3:25 AMursus
05/03/2021, 4:55 AM