ConflatedBufferedChannel的onUndeliveredElement行为及丢数日志方案咨询
环境
使用依赖:org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1
配置capacity = 1的ConflatedBufferedChannel。
当
onBufferOverflow配置为BufferOverflow.DROP_OLDEST时 trySend返回成功。onUndeliveredElement会上报未投递的数字。
输出:
#0 发送成功 #0 已接收 #1 发送成功 #2 发送成功 未投递数字:1 未投递数字:2 未投递数字:3 #3 发送成功 #4 发送成功 #4 已接收
当
onBufferOverflow配置为BufferOverflow.DROP_LATEST时 trySend返回成功。onUndeliveredElement不会上报未投递的数字。
输出:
#0 发送成功 #0 已接收 #1 发送成功 #2 发送成功 #3 发送成功 #4 发送成功 #1 已接收
问题
在此场景下,我们该如何记录被丢弃的数字?
测试代码
fun main() = runBlocking<Unit> { val channel = Channel<Int>(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) { System.err.println("未投递数字:$it") } launch { for (number in channel) { println("#$number 已接收") delay(100) } } launch { repeat(5) { number -> channel.trySend(number) .onSuccess { println("#$number 发送成功") } .onFailure { System.err.println("#$number 发送失败") } delay(5) } } }
内容的提问来源于stack exchange,提问作者toffor
相关产品推荐
相关产品推荐

