Obserables in RxJS are cold by default, and they can be converted to hot Obserables if required. I am thinking about the scenarios for using cold Obserables. For hot Obserables, it seems perfect for handling DOM events or system events. What about cold Obserables? Some fellows mentioned like database query or http requests should use cold Obserables, but for me it sounds better to use hot obserables again to share the result.
Any expert could shed some light on using scenarios for cold obserables?
I would not claim the expert label, but here is my own understanding of cold observables :
They represent a sequence of values whose start point in time is parametrized by the moment of subscription. If we set a time measurement t, x_n to be the nth value of the sequence, t_n the time at the emission of the x_n value, we can represent an observable by (x_n, t_n).
For instance, Rx.Observable.timer(1000) represents the sequence [(1, t_0 +
1000), (2, t_0 +2000), ...] with t_0 representing the time when a subscription occurs. So if you need to represent a sequence of values with relative time, that's the one you need (by the way, you have a function called generateWithRelativeTime to that purpose). For instance, one scenario is do something every second, you would represent 'every second' by the aforementioned observable and the 'do something' by subscribing at the moment of your choice your observer to it.
So, in the same way an array is a container for (x_n) values, the observable is a container for (x_n, t_n) values, the cold observable is a container for (x_n, t_0 + t_n) values, where you decide t_0 (and that is isomorphic to [(x_0,t_0), (x_n, t_n - t_n-1) for n>0]. You decide t_0, the rest in contained in the observable. That is in particular interesting for the testing scenario, as testing is based on creating and controlling test inputs. You can have the same sequence of values flow (same order, same time spacing between values) through various subscribers even if they subscribed at different moments, so you can repeat data flows. You can't repeat button clicks as they happen independently of your observation.
Cold observables are great for database queries etc as it is only executed when you subscribe to the stream. If you were to create a hot observable for a database query, it would be executed straight away, possibly prior to having an subscribers listening to it, so the result could be missed.
There are options where you could reemit the last event whenever a new subscriber attaches to it, but I wouldn't suggest doing that.
Asked in February 2016Viewed 1,681 timesVoted 11Answered 2 times