Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 当新值到达时,周期性地发出最后一个值的流_Kotlin_Kotlin Coroutines - Fatal编程技术网

Kotlin 当新值到达时,周期性地发出最后一个值的流

Kotlin 当新值到达时,周期性地发出最后一个值的流,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我想创建一个Kotlin协程流,当 他们改变了,而且 自上次更改或上次发射后,每隔x个持续时间定期发射最后一个可用值 这似乎有效——每次新值到达时,transformLatest都会取消以前的lambda并启动一个新的lambda。因此,这种方法会发射,然后继续定期发射,直到新值到达为止 flow.transformLatest{value-> while(currentCoroutineContext().isActive){ 发射(值) 延迟(x) } } 您可以创建一个定期发射的流,然后使

我想创建一个Kotlin协程
,当

  • 他们改变了,而且
  • 自上次更改或上次发射后,每隔x个持续时间定期发射最后一个可用值
  • 这似乎有效——每次新值到达时,
    transformLatest
    都会取消以前的lambda并启动一个新的lambda。因此,这种方法会发射,然后继续定期发射,直到新值到达为止

    flow.transformLatest{value->
    while(currentCoroutineContext().isActive){
    发射(值)
    延迟(x)
    }
    }
    
    您可以创建一个定期发射的
    流,然后使用
    组合
    。每次组合这些值时,实际上只是传递您感兴趣的原始
    流的当前值

        // This is the main flow you are interested in.
        val emitter = flow {
            emit("Your data")
            // ...
        }
        // This just serves as a timer.
        val timer = flow {
            // Set this up to emit at a regular interval for as
            // many times as you'd like.
            repeat(100) {
                emit(Unit)
                delay(500)
            }
        }
        // This will emit whenever either of the Flows emits
        combine(
            emitter,
            timer
        ) {  value, ticker ->
            // Always just return the value of your
            // main Flow.
            value
        }
    

    您可以删除
    isActive
    复选框。取消操作的工作原理相同。为True,但
    while
    循环时不会出现任何条件错误。我喜欢明确的检查所提供的额外思维。