Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observables vs. variables in Angular 2 services

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

like image 273
dndr Avatar asked Jan 25 '17 19:01

dndr


People also ask

What is observable in Angular service?

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.

What is observable variable in Angular?

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.

Which is better observables or promises?

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.

What are benefits of observables?

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.


2 Answers

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

like image 199
Günter Zöchbauer Avatar answered Oct 01 '22 01:10

Günter Zöchbauer


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.

like image 45
Ben Richards Avatar answered Oct 03 '22 01:10

Ben Richards