Angular 2 service with observable

New Angular 2 and next versions use pretty interesting thing — rxjs library.
We can use it for easily creating pattern publisher-subscriber (pub/sub).
It is one of the observable pattern realizations.

Take a closer look at the idea. We have an observable object (publisher). It can change value, so we want to be notificated about changes in other parts of the program.
That`s why we subscribe to it.
Every time when observable object changes, subscribers catch this event and get new value.
Similarly we can change the value of observable object anywhere and emit event about change.

Rxjs uses Subject for this. It is a special observer which has the ability both to subscribe to it, emit and catch event from subscribers.

Subject vs BehaviorSubject

But we want both to get the value that came after subscription in subscribers and the value that could be before.
So we need to save the last emitted value.
That is why we use BehaviorSubject instead of just Subject. It helps to get the current value wherever subscription happens.

For clarity there are some examples:

And with BehaviorSubject:

Angular with observable service

So we figured out necessary knowledge, let’s see how pub/sub pattern can be implemented in Angular service.
It is typescript code working in Angular 4, but I think it is correct in Angular 2 too.

Promise vs Observable

Maybe it is not quite clear why observable better then promise.
The good explanatory example is search. When user inputs one letter, we immediately send require to server. But by this moment user has already deleted the letter, so the request is useless.
With observable we can cancel our useless require via one command.

Also promise handles only one event, whereas observable is as a flow of events with callback for each.

Generally observable is similar to array. Accordingly it has analogical methods, for example map.

Eventually — observable is a promise with features.

That`s it! If you have any questions feel free to use the comment section.

Хотите быть в курсе новых статей?