kotlin - 如何从 Kotlin 的 Channel 中读取所有可用元素

标签 kotlin

我想从一个 channel 中读取所有可用的元素,这样如果我的接收器比我的发送器慢,我就可以对它们进行批处理(希望处理批处理的性能更高并允许接收器跟上)。我只想在 channel 为空时暂停,直到我的批次已满或超时才暂停,不像 this question .

标准 kotlin 库中是否内置了任何内容来完成此操作?

最佳答案

我在标准的 kotlin 库中没有找到任何东西,但这是我想出的。这将仅暂停第一个元素,然后是 poll所有剩余的元素。这仅适用于 Buffered Channel以便准备好处理的元素排队并可用于 poll

/**
 * Receive all available elements up to [max]. Suspends for the first element if the channel is empty
 */
internal suspend fun <E> ReceiveChannel<E>.receiveAvailable(max: Int): List<E> {
    if (max <= 0) {
        return emptyList()
    }

    val batch = mutableListOf<E>()
    if (this.isEmpty) {
        // suspend until the next message is ready
        batch.add(receive())
    }

    fun pollUntilMax() = if (batch.size >= max) null else poll()

    // consume all other messages that are ready
    var next = pollUntilMax()
    while (next != null) {
        batch.add(next)
        next = pollUntilMax()
    }

    return batch
}

关于kotlin - 如何从 Kotlin 的 Channel 中读取所有可用元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49618652/

相关文章:

android - 在 Android 的拦截器中执行另一个 API 调用是否有问题?

android - 每次在 Jetpack Compose 中调用导航

python - 如何在 kotlin 中运行 python 函数?

android - 无法访问 Activity 绑定(bind) android

testing - kotlin 多平台覆盖?

spring - 如何避免在执行长时间运行计算的 Spring WebFlux Controller 中使用 Kotlin Coroutines 的 GlobalScope

android - 如何从 Kotlin 中的设置 Activity 中检索首选项?

android - 是否可以将 kotlin 中的高阶函数映射到字符串

kotlin - Unresolved reference :Github上针对Kotlin&Gradle的javafx

kotlin - Ktor 与 Koin DI 无法注入(inject),缺少 clazz