Kotlin TickerModes 之间的区别

Difference between Kotlin TickerModes

我无法理解 Kotlin 代码通道 TickerMode.FIXED_DELAY and TickerMode.FIXED_PERIOD. I've played with both, but I'm unable to draw inferences from their behavior. I've also read the example in the docs 之间的区别。我将不胜感激更清晰的解释,并为每个解释。

正如您在 coroutines sources 中所发现的那样,不同之处在于 FIXED_PERIOD 更加复杂,并且考虑到接收方无法跟上并在下一次调用 [=13= 之前调整延迟的事实].不过,这可能很难演示,因为您需要测量接收器等待下一个滴答声所花费的时间。

P.S。请注意,此功能被标记为 obsolete,即 "the design of the corresponding declarations has serious known flaws and they will be redesigned in the future." 在这种情况下,原因是它没有与结构化并发集成.

fun main() = runBlocking {
    println("\nFIXED_PERIOD")
    val tickerPeriodMode = ticker(100, 0, mode = TickerMode.FIXED_PERIOD)
    consumer(tickerPeriodMode)

    println("\nFIXED_DELAY")
    val tickerDelayMode = ticker(100, 0, mode = TickerMode.FIXED_DELAY)
    consumer(tickerDelayMode)
}

private suspend fun CoroutineScope.consumer(ticker: ReceiveChannel<Unit>) {
    val job = launch {
        var i = 0
        while (isActive) {
            val waitTime = measureTimeMillis {
                ticker.receive()
            }
            print("[%4d ms]".format(waitTime))

            if (i++ == 1) {
                delay(150)
                println(" adding extra 150ms delay")
            } else
                println(" going ahead")
        }
    }
    delay(1_000L)
    job.cancel()
    ticker.cancel() // indicate that no more elements are needed
}

输出

FIXED_PERIOD
[   1 ms] going ahead
[  91 ms] adding extra 150ms delay
[   0 ms] going ahead
[  46 ms] going ahead
[ 100 ms] going ahead
[ 102 ms] going ahead
[  98 ms] going ahead
[ 100 ms] going ahead
[  99 ms] going ahead
[ 100 ms] going ahead
[ 100 ms] going ahead

FIXED_DELAY
[   0 ms] going ahead
[ 105 ms] adding extra 150ms delay
[   0 ms] going ahead
[ 101 ms] going ahead
[ 100 ms] going ahead
[ 103 ms] going ahead
[ 103 ms] going ahead
[ 101 ms] going ahead
[ 101 ms] going ahead
[ 105 ms] going ahead