我正在尝试将一个Observable(String,Date)拆分为两个不同的Observable并将它们压缩在一起,如下所示
import monix.execution.Scheduler.Implicits.global
val x = Observable.fromIterator((0 to 10).map(i => (s"a $i", s"b $i")).toIterator)
val y = Observable.toReactive(x)
val fileStream = Observable.fromReactivePublisher(y).mapAsync(5)(a => Task{println(a._1); a._1})
val dateStream = Observable.fromReactivePublisher(y).mapAsync(5)(a => Task{println(a._2); a._2})
fileStream.zip(dateStream)
.map(println)
.subscribe()
但是我得到了以下异常
monix.reactive.exceptions.MultipleSubscribersException: InputStreamObservable does not support multiple subscribers
at monix.reactive.exceptions.MultipleSubscribersException$.build(MultipleSubscribersException.scala:51)
at monix.reactive.internal.builders.IteratorAsObservable.unsafeSubscribeFn(IteratorAsObservable.scala:42)
at monix.reactive.Observable$$anon$6.subscribe(Observable.scala:155)
at monix.reactive.internal.builders.ReactiveObservable.unsafeSubscribeFn(ReactiveObservable.scala:38)
at monix.reactive.internal.operators.MapAsyncParallelObservable.unsafeSubscribeFn(MapAsyncParallelObservable.scala:60)
at monix.reactive.internal.builders.Zip2Observable.unsafeSubscribeFn(Zip2Observable.scala:158)
at monix.reactive.Observable$$anon$5.unsafeSubscribeFn(Observable.scala:139)
at monix.reactive.Observable$class.subscribe(Observable.scala:71)
at monix.reactive.Observable$$anon$5.subscribe(Observable.scala:136)
at monix.reactive.Observable$class.subscribe(Observable.scala:90)
at monix.reactive.Observable$$anon$5.subscribe(Observable.scala:136)
at monix.reactive.Observable$class.subscribe(Observable.scala:120)
at monix.reactive.Observable$$anon$5.subscribe(Observable.scala:136)
at monix.reactive.Observable$class.subscribe(Observable.scala:112)
at monix.reactive.Observable$$anon$5.subscribe(Observable.scala:136)
答案 0 :(得分:2)
转换为/来自被动是必须的吗?
解决问题的一种方法是val x = Observable.fromIterable((0 to 10).map(i => (s"a $i", s"b $i")))
,但对于无限流,它会出现OutOfMemoryError。
另一种方法是使用.multicast(Pipe.publish[])
,然后使用obs.connect()
代码:
import monix.execution.Scheduler.Implicits.global
val x = Observable.fromIterator((0 to 10).map(i => (s"a $i", s"b $i")).iterator)
val y = Observable.toReactive(x)
val obsY = Observable.fromReactivePublisher(y)
val connectY = obsY.multicast(Pipe.publish[(String, String)])
val fileStream = connectY.mapAsync(5)(a => Task{println(a._1); a._1})
val dateStream = connectY.mapAsync(5)(a => Task{println(a._2); a._2})
fileStream.zip(dateStream)
.map(println)
.subscribe()
connectY.connect()
Thread.sleep(5000)
答案 1 :(得分:0)
除了sergei-shubin的回答外,还可以将Observable
临时转换为“热”可观察对象,可以使用publishSelector
将其拆分为多个流,而无需手动处理{{1 }}。看起来像这样:
multicast