Inovaro_NL
Inovaro_NL

Reputation: 33

Observable.of(array) updates every time setInterval is fired

I’m having some weird behaviour when using Observable.of(array) and angular’s async pipe. Maybe I’m using it wrong but I can’t understand it.

I have a view.html and view.ts file in Ionic 3 (angular 4). I’m doing a Observable.of(items). Items is just an array with objects. And in my view I have: let item of items | async. It all works great but when I also do a setInterval in the view.ts every 1000 miliseconds... the view updates every 1000 miliseconds. Even when the setInterval doesn’t do anything!

Am I using it wrong? I can’t understand the behaviour..!

Upvotes: 0

Views: 575

Answers (2)

André Werlang
André Werlang

Reputation: 5944

Use OnPush strategy. With this strategy only impacted items are evaluated, that is, components where events fired or otherwise were marked for check. Also, items are compared in shallow mode, that means only references are checked. This requires you to not mutate objects.

Import ChangeDetectionStrategy from @angular/core, then add changeDetection: ChangeDetectionStrategy.OnPush to the @Component decorator.

For instance, instead of this.array.push(value) use this.array = this.array.concat(value).

When the value is updated asynchronously, like in an http call or timer, add ChangeDetectorRef and call markForCheck() on the callback.

Upvotes: 0

Jota.Toledo
Jota.Toledo

Reputation: 28434

The setInterval method is "patched" in such a way, that it triggers a change detection cycle.

Take a look here for more info.

Some relevant sections of the link:

Basically application state change can be caused by three things:

Events - click, submit, …

XHR - Fetching data from a remote server

Timers - setTimeout(), setInterval()

They are all asynchronous. Which brings us to the conclusion that, basically whenever some asynchronous operation has been performed, our application state might have changed. This is when someone needs to tell Angular to update the view.

Who notifies Angular?

Alright, we now know what causes application state change. But what is it that tells Angular, that at this particular moment, the view has to be updated? Angular allows us to use native APIs directly. There are no interceptor methods we have to call so Angular gets notified to update the DOM. Is that pure magic? If you’ve followed our latest articles, you know that Zones take care of this. In fact, Angular comes with its own zone called NgZone, which we’ve written about in our article Zones in Angular. You might want to read that, too. The short version is, that somewhere in Angular’s source code, there’s this thing called ApplicationRef, which listens to NgZones onTurnDone event. Whenever this event is fired, it executes a tick() function which essentially performs change detection.

Upvotes: 1

Related Questions