I have a question regarding the use of Observables vs. variables in Angular 2 services. The former seems to be the preferred way, but I cannot find out why exactly.
Given a sample service such as this:
@Injectable()
export class TestService {
// Method 1
public data = {x: Math.random(), y: Math.random()};
// Method 2
private _data$:BehaviorSubject<any> = new BehaviorSubject({x: Math.random(), y: Math.random()});
public data$:Observable<any> = this._data$.asObservable();
constructor() {
setInterval(() => {
this.data = {x: Math.random(), y: Math.random()};
this._data$.next({x: Math.random(), y: Math.random()});
}, 500);
}
}
I have seen basically 2 ways of consuming data in a component. Just using a variable directly:
<pre>{{testService.data | json}}</pre>
And using an Observable:
<pre>{{(testService.data | async) | json}}</pre>
Both seem to work, so what's the advantage of using the more elaborate Observable-based approach?
Plunker: https://plnkr.co/edit/1qVDSZwq2NVgZsWFPnii?p=preview
Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.
Angular observables The observable can deliver multiple values of any type like literals, messages, or events, depending on the context. For example, ass a publisher, you can create an Observable instance that defines a subscriber function. This function is executed when the consumer calls the subscribe() method.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
You can often use observables instead of promises to deliver values asynchronously. Similarly, observables can take the place of event handlers. Finally, because observables deliver multiple values, you can use them where you might otherwise build and operate on arrays.
Observables push value changes to components and services that subscribe to changes.
A variable requires polling, Therefore it's a huge performance benefit.
Especially if there are timing issues, for example the component wants a value from a service that the service fetches from the server. How does the component know about the value becoming available.
With an observable the component just subscribes and gets called when the value arrived.
Angulars change detection directly supports observables.
When the ChangeDetectionStrategy.OnPush
is used and the view binds to an observable using the async pipe (<div>{{myObservable | async}}</div>
), then change detection is not run at all except when a new value is pushed by the observable.
Observables have other benefits. See for example https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
The difference is that observables are a stream, and you can have more than one subscriber to the stream. And you also get all the advantages of a stream - hot, cold obervables, reply, filters, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With