Kotlin协程flow的debounce参数timeoutMillis特性

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发现流中已没有数据等待,就直接舍弃之前数据,只发射最后一条。

扫描二维码关注公众号,回复: 16431460 查看本文章

Kotlin协程flow发送时间间隔debounce_zhangphil的博客-CSDN博客debounce蕴含了一定的缓冲思想,即,不立刻触发事件,而是先把要发射的数据进入队列,稍等一定时间(时间)延迟触发,而触发的重要条件取决于前一条数据和后一条数据的时间间隔,注意,前一条和后一条尚未被发射出去,只是待命中。发射完ABC,Kotlin审视待发射的ABCD,按理说ABCD与ABC间隔200,满足发射timeOut值,但是ABCD与ABCDE间隔100,所以跳过ABCD,直接发射ABCDE。四、map,重组改写数据。A和AB都待发射,A和AB间隔100,所以跳过A,直接发射AB。https://blog.csdn.net/zhangphil/article/details/132515686

kotlin协程flow filter map flowOn zip combine(1)_zhangphil的博客-CSDN博客一、flow ,emit,onCompletion,collect。四、map,重组改写数据。八、conflate 合并。九、debounce去重。二、函数作为flow。https://blog.csdn.net/zhangphil/article/details/130084723

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/132525869