5

I know that the difference between hot and cold observables has been previously discussed on Stack Overflow in the context of C#, however I don't know C# at all and don't understand the code examples Lee Campbell refers to.

I'm working in Scala, using the RXScala library. What are hot and cold observables in Scala, and how are they implemented using RXScala?

Community
  • 1
  • 1
jhegedus
  • 20,244
  • 16
  • 99
  • 167
  • 2
    You may want to read my blog post on [Hot and Cold Observables](http://davesexton.com/blog/post/Hot-and-Cold-Observables.aspx). I use very little code examples. It's almost entirely a deep dive into theory. – Dave Sexton Jan 19 '15 at 11:47

1 Answers1

6

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.

candied_orange
  • 7,036
  • 2
  • 28
  • 62
phadej
  • 11,947
  • 41
  • 78