티스토리 뷰
Use case
When we have filter/search functionality in our app, we often want to trigger an operation whenver user enters query in an EditText and we want to reduce network calls by using debouncing. Kotlin Flow supports debouce operation but it's still preview until 1.6.
So, if we use Kotlin lower than 1.6.10, then we are unlikey to use Flow.debounce.
Alternative of this would be collectLatest + delay.
suspend fun <T> Flow<T>.collectDebounce(timeMillis: Long, action: suspend (T) -> Unit) {
this.collectLatest {
delay(timeMillis)
action(it)
}
}
The way it works is that collectLatest will cancel the previous collecting if new item arrives. So, we just simply put some delay before collecting. With mutableShardFlow, we can easily acheive deboucing.
// ViewModel
private val queryFlow = MutableSharedFlow("")
init {
queryFlow
.collectDebounce(1000L) {
fetchData()
}
}
fun queryEntered(query: String) {
queryFlow.value = query
}
댓글