A Collection of Items Over Time
The Observable is a new type that has been introduced 5 years ago by Microsoft’s Reactive Extensions library. This is my attempt to introduce them in simple terms.
An Observable is just a collection of items over time.
This is a really great succinct description for Observables and it comes from
an epiphany Jafar had when he was working at Microsoft and Erik Meijer asked him this (I am paraphrasing):
What is the difference between a collection and an event?
When you look at the two side-by-side on a higher level there is really not much separating them:
Really they are the same. They are both collections. One is a collection in space and the other is a collection on a timeline.
Looking at events in this way led to the conclusion that you should be able to transform event data being pushed to you in the same way as you can with collections.
What does that mean?
One of those array functions is “map”. Map iterates over the original array
and passes every item of the original array to a callback. The callback
then can do something with that item and whatever that function returns
becomes an item in the resulting new array which has the same length as the original array.
Here is a simple example with our coordinates array in which we transform
the coordinates array to an array containing just the x-coordinates:
Now we have an array containing the values of the x-coordinates but we are
only interested in the x-coordinates that are greater than 2.
Thankfully we can simply chain the “filter” function with the map function.
The filter functions iterates over the array and returns a new array containing all the items that the callback function that was passed to filter returns “true” for.
And this is how we do it:
So now we have an array with just the two x-values that are greater than 2
and can do something in the UI with it.
OK, remember how I said that with Observable we’re able to do the same thing with data that is being pushed to us?
Take for example a stream of mouseclick events. Imagine that for some reason we want to immediately react to every mouseclick on the document but only the ones with the x-coordinate greater than 100.
With Observables we can do this just by using array functions.
Granted this example is very simplistic but nonetheless it shows the power
of the original idea that events are just collections on a timeline. Instead
of resulting in an array (a collection in space) the data drips through the
array functions one by one (a collection in time) and can be dealt with in
the subscribe function one by one.