【问题标题】:Is there a Kotlin coroutine channel that behaves like XStream Stream?有没有像 XStream Stream 一样的 Kotlin 协程通道?
【发布时间】:2018-07-06 10:22:59
【问题描述】:

我想要一个行为类似于XStream Stream的协程通道

  1. send 到频道始终是非阻塞的
  2. 没有缓冲区,如果没有接收器,值会“丢失”。
  3. 新订阅者没有获得最后一个值。
  4. 所有订阅者都会收到所有值(如BroadcastChannel

我找到的最接近的是ConflatedBroadcastChannel,但是这个“记住”最后一个值,使它像XStream MemoryStream

是否有解决方法来获得我的确切语义?

【问题讨论】:

    标签: kotlin kotlinx.coroutines


    【解决方案1】:

    不,没有这样的频道,请随时create an issue

    您可以采用的最接近的解决方法是在 ConflatedBroadcastChannel 上提供一个扩展,这将丢弃现有元素:

    fun <T> ConflatedBroadcastChannel<T>.subscription(): ReceiveChannel<T> {
        val subscription = openSubscription()
        subscription.poll()
        return subscription
    }
    

    从消费者的角度来看,这个订阅的语义和XStream是一样的,但是它不符合“没有缓冲区”的部分:发送的元素会被保存在内存中(~不能被垃圾回收) 直到下一个 send 被调用。

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2020-04-12
      • 2021-06-18
      • 1970-01-01
      • 2014-06-06
      • 2021-10-28
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      相关资源
      最近更新 更多