Search code examples
scalaobservablemongo-scala-driver

Seq of observable to observable


I use mongo-scala-driver 1.0.1 that return Observable[Completed] after insertMany.

I put many documents in cycle and I need to do some action after all of it already inserted.

I can use observable.toFuture to get Seq[Future[Completed]] and then Future.sequence(...) to handle future.

But is it possible to transform Seq[Observable[Completed]] to Observable[...] in Scala? Or there is a better way to handle it?

mongo-scala-driver has it's own Observable trait org.mongodb.scala.Observable


Solution

  • Here is an example of how to flatten List of Observables into single Observable.

    List(
      Observable.interval(200 millis),
      Observable.interval(400 millis),
      Observable.interval(800 millis)
    ).toObservable.flatten.take(12).toBlocking.foreach(println(_))
    

    You can find this and many more examples here: https://github.com/ReactiveX/RxScala/blob/0.x/examples/src/test/scala/examples/RxScalaDemo.scala

    Edit

    Here is what should work with mongo api, although I didn't test it.

    val observables: Seq[Observable[Int]] = ???
    val result: Observable[Int] = Observable(observables).flatMap(identity)