The Rx Pattern and the Observable

While the Observer and the Iterator patterns are powerful in their own right, the combination of both is even better. We call this the Rx pattern, named after the Reactive Extensions libraries.[11] We’ll be using this pattern for the rest of the book.

The Observable sequence, or simply Observable is central to the Rx pattern. An Observable emits its values in order—like an iterator—but instead of its consumers requesting the next value, the Observable “pushes” values to consumers as they become available. It has a similar role to the Producer’s in the Observer pattern: emitting values and pushing them to its listeners.

Put more simply, an Observable is a sequence whose items become available over time. The consumers of Observables, Subscriptions, are the equivalent of listeners in the Observer pattern. When a Subscription subscribes to an Observable, it receives the values in the sequence as they become available, without having to request them.

So far it doesn’t seem very different from the traditional Observer pattern. But actually there are two essential differences:

  • An Observable doesn’t start streaming items until it has at least one Observer subscribed to it.

  • Like iterators, an Observable can signal when the sequence is completed.

Using Observables, we can declare how to react to the sequence of elements, instead of reacting to individual items. We can efficiently copy, transform, and query the sequence, and these operations will apply to all the elements of the sequence.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.225