Kotlin协程flow的debounce参数timeoutMillis特性
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>1.7.3</version>
<type>pom</type>
</dependency>
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) {
runBlocking {
launch {
(1..5).asFlow().onEach {
println("delay> ${System.currentTimeMillis()}")
delay(1)
println("delay< ${System.currentTimeMillis()}")
println("-$it-")
}.debounce(999999).collect {
println("-----")
println("$it-@${System.currentTimeMillis()}")
}
}
}
}
注意观察输出结果:
delay> 1693130447124
delay< 1693130447129
-1-
delay> 1693130447131
delay< 1693130447138
-2-
delay> 1693130447138
delay< 1693130447147
-3-
delay> 1693130447147
delay< 1693130447162
-4-
delay> 1693130447162
delay< 1693130447177
-5-
-----
5-@1693130447180
每次发射的delay()时间非常短,只有1毫秒,显然都不能达到给debounce设置的弹跳时间(999999),但是当Kotlin发现流中已没有数据等待,就直接舍弃之前数据,只发射最后一条。