Kotlin TickerModes之间的区别

时间:2018-12-19 03:40:54

标签: kotlin kotlinx.coroutines

我无法理解Kotlin代码通道TickerMode.FIXED_DELAY and TickerMode.FIXED_PERIOD之间的区别。我都玩过,但是我无法从他们的行为中得出推论。我还阅读了docs中的示例。我希望能得到更清晰的解释,并附上每种解释。

1 个答案:

答案 0 :(得分:1)

正如您在coroutines sources中发现的,不同之处在于FIXED_PERIOD更复杂,并且考虑到接收者无法跟上并调整下一次调用send之前的延迟这一事实。但是,这可能很难演示,因为您需要测量接收者等待下一个刻度的时间。

P.S。请注意,此功能标记为过时,即“相应声明的设计存在严重的已知缺陷,以后将对其进行重新设计。” 在这种情况下,原因它没有与结构化并发集成。

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