Nino
10/11/2022, 10:15 AMupdateFoo(foo: String?)
can be called any number of time, from multiple different coroutines
2/ A Flow should be available to emit the "last value that went through `updateFoo`", but should not emit quicker than every 100ms
3/ The flow should not re-emit similar values
4/ This is the bad part, the Flow should emit null values immediately
My approach :
companion object {
private val SAMPLE_DURATION = 100.milliseconds
}
private val fooMutableStateFlow = MutableStateFlow<String?>(null)
val fooFlow: Flow<String?> = fooMutableStateFlow
.sample(SAMPLE_DURATION)
.onStart { emit(fooMutableStateFlow.value) }
.distinctUntilChanged() // Avoid double emission of null value with .onStart...
fun updateFoo(foo: String?) {
fooMutableStateFlow.value = foo
}
I'd love an operator like debounce so I could do something like that :
val fooFlow: Flow<String?> = fooMutableStateFlow.sample {
if (it == null) {
Duration.ZERO
} else {
Toto.SAMPLE_DURATION
}
}
ephemient
10/11/2022, 10:34 AM(T) -> timeout
lambda, does that do what you want?Nino
10/11/2022, 10:37 AMephemient
10/11/2022, 10:38 AMNino
10/11/2022, 10:40 AMFrancis Reynders
10/13/2022, 11:47 AMval fooFlow = merge(
fooMutableStateFlow
.filterNotNull()
.sample<String>(SAMPLE_DURATION),
fooMutableStateFlow
.filter { it == null })
.onStart { emit(fooMutableStateFlow.value) }
.distinctUntilChanged()
Nino
10/13/2022, 12:23 PMval fooFlow : Flow<String?> = fooMutableStateFlow
.distinctUntilChangedBy { it == null }
.flatMapLatest {
if (it == null) {
flowOf(null)
} else {
fooMutableStateFlow.sample(SAMPLE_DURATION)
}
}
I did something similar but with flatMap
in the end...Francis Reynders
10/13/2022, 2:48 PM