Kotlin TickerModes之间的区别
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kotlin TickerModes之间的区别相关的知识,希望对你有一定的参考价值。
我无法理解Kotlin股票频道TickerMode.FIXED_DELAY
and TickerMode.FIXED_PERIOD
之间的区别。我和两个人一起玩过,但我无法从他们的行为中得出推论。我也读过docs中的例子。我将感激更清楚的解释,并举例说明。
答案
正如你在coroutines sources中所发现的那样,不同之处在于FIXED_PERIOD
更复杂,并且考虑到接收器无法跟上并在下次调用send
之前调整延迟的事实。尽管如此,这可能很棘手,因为你需要测量接收器等待下一个滴答的时间。
附:请注意,此功能被标记为过时,即“相应声明的设计具有严重的已知缺陷,并且将来会重新设计。”在这种情况下,原因是它没有与结构化并发集成。
fun main() = runBlocking {
println("
FIXED_PERIOD")
val tickerPeriodMode = ticker(100, 0, mode = TickerMode.FIXED_PERIOD)
consumer(tickerPeriodMode)
println("
FIXED_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
以上是关于Kotlin TickerModes之间的区别的主要内容,如果未能解决你的问题,请参考以下文章
使用 Kotlin 的 RxJava 中的花括号和普通括号有啥区别