Cold observables
Cold observables are observables which start producing values when subscribed.
Streams that are passive and start publishing on request.
Some examples:
import rx.lang.scala._
import org.joda.time._
val onetwothree = Observable.just(1, 2, 3) // when subscribed each subscriber will get 1, 2, and 3
// scala> onetwothree.subscribe(println(_))
// 1
// 2
// 3
// res1: rx.lang.scala.Subscription = rx.lang.scala.Subscription$$anon$2@11be372a
// When subscribed will get one event with current DateTime
val currentTime = Observable.defer {
Observable.just(DateTime.now)
}
// scala> currentTime.subscribe(println(_))
// 2015-01-19T14:13:37.333+02:00
// scala> currentTime.subscribe(println(_))
// 2015-01-19T14:13:38.742+02:00
// scala> currentTime.subscribe(println(_))
// 2015-01-19T14:13:40.448+02:00
// And this one is tricky.
val loggedInUsers = Obserable.defer {
fetchLoggedUsersFromDb
}
Hot observables
Streams that are active and publish regardless of subscriptions.
The natural example is from UI programming: the stream of mouse clicks. The clicks are produced regardless of whether or not the stream is subscribed to.
In many applications loggedInUsers
is made into something one might call warm observable:
val loggedInUsers = updateTriggers.concatMap { _ =>
fetchLoggedUsersFromDb
}.replay(1)
The subsriber of this stream will immediately get one value, logged users, when the updateTriggers
was triggered last time. And also the consecutive updates.
Warm observables
val hot = mouseClicks
// Observable that will replay all of its items and notifications to any future Observer
// i.e. all mouseClicks from the time point we called `.replay`
val cold = hot.replay
But there is something in between:
// Observable that will replay at most 10 items emitted by `hot`
val warm = hot.replay(10)
When we subscribe to warm
it will immediately emit last 10 clicks, and continue emit clicks coming after that.