Monix看起来很棒,但文档非常稀疏。
monix中akka-streams的alsoTo
类似物是什么?
基本上我希望两个消费者都能使用流。
答案 0 :(得分:3)
Monix遵循Rx模型,订阅是动态的。任何Observable
都支持无限数量的订阅者:
val obs = Observable.interval(1.second)
val s1 = obs.dump("O1").subscribe()
val s2 = obs.dump("O2").subscribe()
但是有一个问题 - Observable
默认情况下称为“冷数据源”,这意味着每个订阅者都有自己的数据源。
例如,如果您有Observable
从File
读取,那么每个订阅者都会获得自己的文件句柄。
为了在多个订阅者之间“共享”此类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