티스토리 뷰

Kotlin/Flow

Debounce using Flow + collectLatest

Kaboomba 2022. 3. 16. 10:09

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. 

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/debounce.html

 

debounce

debounce common Returns a flow that mirrors the original flow, but filters out values that are followed by the newer values within the given timeout. The latest value is always emitted. Example: flow { emit(1) delay(90) emit(2) delay(90) emit(3) delay(1010

kotlin.github.io

 

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
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함