首页 > 解决方案 > Kotlin TickerMode 之间的区别

问题描述

我无法理解 Kotlin 股票频道TickerMode.FIXED_DELAYTickerMode.FIXED_PERIOD. 我都玩过,但我无法从他们的行为中得出推论。我还阅读了文档中的示例。如果有更清晰的解释,我将不胜感激,并附有说明。

标签: kotlinkotlinx.coroutines

解决方案


正如您在协程源中发现的那样,区别在于它FIXED_PERIOD更复杂,并且考虑到接收器无法跟上并在下次调用send. 但是,这可能很难证明,因为您需要测量接收器等待下一个滴答声所花费的时间。

PS 请注意,此功能被标记为obsolete,即“相应声明的设计存在严重的已知缺陷,未来将重新设计”。在这种情况下,原因是它没有与结构化并发集成。

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

推荐阅读