什么是monix中akka-streams的'alsoTo`类似物?

时间:2018-02-13 12:31:40

标签: scala monix

Monix看起来很棒,但文档非常稀疏。

monix中akka-streams的alsoTo类似物是什么?

基本上我希望两个消费者都能使用流。

1 个答案:

答案 0 :(得分:3)

Monix遵循Rx模型,订阅是动态的。任何Observable都支持无限数量的订阅者:

val obs = Observable.interval(1.second)

val s1 = obs.dump("O1").subscribe()
val s2 = obs.dump("O2").subscribe()

但是有一个问题 - Observable默认情况下称为“冷数据源”,这意味着每个订阅者都有自己的数据源。

例如,如果您有ObservableFile读取,那么每个订阅者都会获得自己的文件句柄。

为了在多个订阅者之间“共享”此类Observable,您必须将其转换为热数据源才能共享。您可以使用multicast运算符及其最常用的publish版本。这些回复了ConnectableObservable,需要connect()来启动流式传输:

val shared = obs.publish

// Nothing happens here:
val s1 = shared.dump("O1").subscribe()
val s2 = shared.dump("O2").subscribe()

// Starts actual streaming
val cancelable = shared.connect()

// You can subscribe after connect(), but you might lose events:
val s3 = shared.dump("O3").subscribe()

// You can unsubscribe one of your subscribers, but the
// data source keeps the stream active for the others
s1.cancel()

// To cancel the connection for all subscribers:
cancelable.cancel()

PS:monix.io正在进行中,欢迎PR