【问题标题】:How to keep track of the number of emits in flowable?如何跟踪 flowable 中的发射次数?
【发布时间】:2019-02-22 23:57:07
【问题描述】:

假设我有一个 flowable,订阅了一些视图并且它正在监听更改。我想添加一个自定义方法,该方法仅基于 flowable 的第一次发射,但也保留其他侦听更改的方法。处理它的最佳方法是什么? 我采用的天真的方法是复制可流动的并将其转换为 Single 或 Completable 以获得结果,但这似乎是多余的。

谢谢。

【问题讨论】:

  • 标题与描述不符。

标签: android rx-java rx-java2


【解决方案1】:

使用.take(1)。顺便说一句,还要确保 flowable 是共享的(否则一些观察者会错过事件)。

【讨论】:

    【解决方案2】:

    我认为您可以为此使用share 运算符。 Share 操作员生成一个 Connectable Observable。然后 Connectable Observable 发布每个订阅的项目。

    val o = Flowable.fromArray(1, 2, 3, 4, 5)
        .map {
            println("heavy operation")
            it + it
        }
        .share() // publish the changes
        .subscribeOn(Schedulers.computation()) // for testing. change what you want
    
    o.take(1).subscribe { println("Special work: $it") } // take one
    
    o.subscribe { println("Normal work: $it") }
    

    结果

    heavy operation
    Special work: 2
    Normal work: 2
    heavy operation
    Normal work: 4
    heavy operation
    Normal work: 6
    heavy operation
    Normal work: 8
    heavy operation
    Normal work: 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      相关资源
      最近更新 更多