0

Monix looks like great framework but documentation is very sparse.

What is alsoTo analogue of akka-streams in monix ?

Basically I want stream to be consumed by two consumers.

expert
  • 29,290
  • 30
  • 110
  • 214

1 Answers1

3

Monix follows the Rx model in that subscriptions are dynamic. Any Observable supports an unlimited number of subscribers:

val obs = Observable.interval(1.second)

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

There is a catch however — Observable is by default what is called a "cold data source", meaning that each subscriber gets its own data source.

So for example, if you had an Observable that reads from a File, then each subscriber would get its own file handle.

In order to "share" such an Observable between multiple subscribers, you have to convert it into a hot data source, to share it. You do so with the multicast operator and its versions, publish being most commonly used. These give you back a ConnectableObservable, that needs a connect() call to start the streaming:

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 is a work in progress, PRs are welcome

Alexandru Nedelcu
  • 8,061
  • 2
  • 34
  • 39