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.
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 😀
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.