You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 17:25:07