kotlin - Kotlin TickerMode 之间的区别
问题描述
我无法理解 Kotlin 股票频道TickerMode.FIXED_DELAY
和TickerMode.FIXED_PERIOD
. 我都玩过,但我无法从他们的行为中得出推论。我还阅读了文档中的示例。如果有更清晰的解释,我将不胜感激,并附有说明。
解决方案
正如您在协程源中发现的那样,区别在于它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
推荐阅读
- android - 在使用 Detox 运行测试期间,Android 模拟器无法启动应用程序
- node.js - 反应路由器是否覆盖 app.get('/ping' 的 URL 路由?
- php - PHP 在多查询中从 db 中检索数据并打印 json
- java - 将 Future 转换为 Mono
- c++ - 在方法的参数化构造函数中调用参数 - C++
- php - 无法使用 ZipArchive 将文件保存在 ZIP 中
- c# - 错误 java.lang.IllegalArgumentException:已添加:Lokio/AsyncTimeout
- java - PDFBox 渲染 Jpeg2000 和 JBIG2
- c++ - 错误错误:在初始化列表中,非常量表达式不能从“unsigned long”类型缩小到“char”
- angular - Angular 9 库构建错误:找不到节点的导出名称