Angular Change Detection with Observable timer










1














Background:



I have a number of components in my Angular 6 application that are required to display the current time (hh:mm).



These were initially implemented using setInterval with this.now being bound in the view:



setInterval(() => 
this.now = new Date();
, 1000);


Naturally, this causes change detection to run every second which is wasteful given the value will only update once per minute. I can improve this by running the setInterval outside of ngZone and manually triggering change detection if the minute has rolled over.



Question:



I'm trying to implement an observable stream of dates which emit a new value every minute. This is what I have do far...



timer(0, 1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date => console.log(date))
);


A new date is emitted once per minute however subscribing to this stream causes Angular's change detection to run every second. (I confirmed this by adding a ngDoCheck to a component that subscribe).



How can I defer change detection so it only occurs when a new value is emitted?










share|improve this question





















  • What are you trying to do?
    – Microsmsm
    Nov 12 '18 at 0:30










  • Change detection usually happens in a recursion loop
    – Microsmsm
    Nov 12 '18 at 0:31







  • 1




    Did you try Observable.interval(1000) ?
    – Microsmsm
    Nov 12 '18 at 0:32










  • Sorry if it wasn't clear: "I'm trying to implement an observable stream of dates which emit a new value every minute." however I only want change detection to trigger when a value is emitted, not every 1000ms when the timer fires.
    – MS_AU
    Nov 12 '18 at 0:58











  • run it outside angular zone and set manual changing for value: blog.angularindepth.com/…
    – Microsmsm
    Nov 12 '18 at 1:28















1














Background:



I have a number of components in my Angular 6 application that are required to display the current time (hh:mm).



These were initially implemented using setInterval with this.now being bound in the view:



setInterval(() => 
this.now = new Date();
, 1000);


Naturally, this causes change detection to run every second which is wasteful given the value will only update once per minute. I can improve this by running the setInterval outside of ngZone and manually triggering change detection if the minute has rolled over.



Question:



I'm trying to implement an observable stream of dates which emit a new value every minute. This is what I have do far...



timer(0, 1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date => console.log(date))
);


A new date is emitted once per minute however subscribing to this stream causes Angular's change detection to run every second. (I confirmed this by adding a ngDoCheck to a component that subscribe).



How can I defer change detection so it only occurs when a new value is emitted?










share|improve this question





















  • What are you trying to do?
    – Microsmsm
    Nov 12 '18 at 0:30










  • Change detection usually happens in a recursion loop
    – Microsmsm
    Nov 12 '18 at 0:31







  • 1




    Did you try Observable.interval(1000) ?
    – Microsmsm
    Nov 12 '18 at 0:32










  • Sorry if it wasn't clear: "I'm trying to implement an observable stream of dates which emit a new value every minute." however I only want change detection to trigger when a value is emitted, not every 1000ms when the timer fires.
    – MS_AU
    Nov 12 '18 at 0:58











  • run it outside angular zone and set manual changing for value: blog.angularindepth.com/…
    – Microsmsm
    Nov 12 '18 at 1:28













1












1








1







Background:



I have a number of components in my Angular 6 application that are required to display the current time (hh:mm).



These were initially implemented using setInterval with this.now being bound in the view:



setInterval(() => 
this.now = new Date();
, 1000);


Naturally, this causes change detection to run every second which is wasteful given the value will only update once per minute. I can improve this by running the setInterval outside of ngZone and manually triggering change detection if the minute has rolled over.



Question:



I'm trying to implement an observable stream of dates which emit a new value every minute. This is what I have do far...



timer(0, 1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date => console.log(date))
);


A new date is emitted once per minute however subscribing to this stream causes Angular's change detection to run every second. (I confirmed this by adding a ngDoCheck to a component that subscribe).



How can I defer change detection so it only occurs when a new value is emitted?










share|improve this question













Background:



I have a number of components in my Angular 6 application that are required to display the current time (hh:mm).



These were initially implemented using setInterval with this.now being bound in the view:



setInterval(() => 
this.now = new Date();
, 1000);


Naturally, this causes change detection to run every second which is wasteful given the value will only update once per minute. I can improve this by running the setInterval outside of ngZone and manually triggering change detection if the minute has rolled over.



Question:



I'm trying to implement an observable stream of dates which emit a new value every minute. This is what I have do far...



timer(0, 1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date => console.log(date))
);


A new date is emitted once per minute however subscribing to this stream causes Angular's change detection to run every second. (I confirmed this by adding a ngDoCheck to a component that subscribe).



How can I defer change detection so it only occurs when a new value is emitted?







angular rxjs observable






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 '18 at 23:36









MS_AU

816




816











  • What are you trying to do?
    – Microsmsm
    Nov 12 '18 at 0:30










  • Change detection usually happens in a recursion loop
    – Microsmsm
    Nov 12 '18 at 0:31







  • 1




    Did you try Observable.interval(1000) ?
    – Microsmsm
    Nov 12 '18 at 0:32










  • Sorry if it wasn't clear: "I'm trying to implement an observable stream of dates which emit a new value every minute." however I only want change detection to trigger when a value is emitted, not every 1000ms when the timer fires.
    – MS_AU
    Nov 12 '18 at 0:58











  • run it outside angular zone and set manual changing for value: blog.angularindepth.com/…
    – Microsmsm
    Nov 12 '18 at 1:28
















  • What are you trying to do?
    – Microsmsm
    Nov 12 '18 at 0:30










  • Change detection usually happens in a recursion loop
    – Microsmsm
    Nov 12 '18 at 0:31







  • 1




    Did you try Observable.interval(1000) ?
    – Microsmsm
    Nov 12 '18 at 0:32










  • Sorry if it wasn't clear: "I'm trying to implement an observable stream of dates which emit a new value every minute." however I only want change detection to trigger when a value is emitted, not every 1000ms when the timer fires.
    – MS_AU
    Nov 12 '18 at 0:58











  • run it outside angular zone and set manual changing for value: blog.angularindepth.com/…
    – Microsmsm
    Nov 12 '18 at 1:28















What are you trying to do?
– Microsmsm
Nov 12 '18 at 0:30




What are you trying to do?
– Microsmsm
Nov 12 '18 at 0:30












Change detection usually happens in a recursion loop
– Microsmsm
Nov 12 '18 at 0:31





Change detection usually happens in a recursion loop
– Microsmsm
Nov 12 '18 at 0:31





1




1




Did you try Observable.interval(1000) ?
– Microsmsm
Nov 12 '18 at 0:32




Did you try Observable.interval(1000) ?
– Microsmsm
Nov 12 '18 at 0:32












Sorry if it wasn't clear: "I'm trying to implement an observable stream of dates which emit a new value every minute." however I only want change detection to trigger when a value is emitted, not every 1000ms when the timer fires.
– MS_AU
Nov 12 '18 at 0:58





Sorry if it wasn't clear: "I'm trying to implement an observable stream of dates which emit a new value every minute." however I only want change detection to trigger when a value is emitted, not every 1000ms when the timer fires.
– MS_AU
Nov 12 '18 at 0:58













run it outside angular zone and set manual changing for value: blog.angularindepth.com/…
– Microsmsm
Nov 12 '18 at 1:28




run it outside angular zone and set manual changing for value: blog.angularindepth.com/…
– Microsmsm
Nov 12 '18 at 1:28












1 Answer
1






active

oldest

votes


















0














You can use a subject and interval for this i guess maybe some way like this :



Basically in your code where you have implemented this(assuming it is a separate service : some.service.ts ) , define a subject like this :



someSubject : Subject<Date> = new Subject<Date>();

interval(1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date =>
console.log(date);
this.someSubject.next(date);
);
).subscribe();


Subscribe to the someSubject from wherever you want to listen to the date change like this :



this._someService.someSubject.subscribe((date : Date) =>
console.log(date); //you'll have a new date object everytime your date object changes i.e everyminute
);


don't forget to import interval from rxjs



i have created an example(listen for every second change) using StackBlitz : https://stackblitz.com/edit/angular-4ytdbs






share|improve this answer




















  • Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
    – MS_AU
    Nov 12 '18 at 23:35











  • @MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
    – CruelEngine
    Nov 13 '18 at 8:19










  • Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
    – MS_AU
    Nov 13 '18 at 10:59










  • @MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
    – CruelEngine
    Nov 13 '18 at 12:44










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254339%2fangular-change-detection-with-observable-timer%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can use a subject and interval for this i guess maybe some way like this :



Basically in your code where you have implemented this(assuming it is a separate service : some.service.ts ) , define a subject like this :



someSubject : Subject<Date> = new Subject<Date>();

interval(1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date =>
console.log(date);
this.someSubject.next(date);
);
).subscribe();


Subscribe to the someSubject from wherever you want to listen to the date change like this :



this._someService.someSubject.subscribe((date : Date) =>
console.log(date); //you'll have a new date object everytime your date object changes i.e everyminute
);


don't forget to import interval from rxjs



i have created an example(listen for every second change) using StackBlitz : https://stackblitz.com/edit/angular-4ytdbs






share|improve this answer




















  • Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
    – MS_AU
    Nov 12 '18 at 23:35











  • @MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
    – CruelEngine
    Nov 13 '18 at 8:19










  • Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
    – MS_AU
    Nov 13 '18 at 10:59










  • @MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
    – CruelEngine
    Nov 13 '18 at 12:44















0














You can use a subject and interval for this i guess maybe some way like this :



Basically in your code where you have implemented this(assuming it is a separate service : some.service.ts ) , define a subject like this :



someSubject : Subject<Date> = new Subject<Date>();

interval(1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date =>
console.log(date);
this.someSubject.next(date);
);
).subscribe();


Subscribe to the someSubject from wherever you want to listen to the date change like this :



this._someService.someSubject.subscribe((date : Date) =>
console.log(date); //you'll have a new date object everytime your date object changes i.e everyminute
);


don't forget to import interval from rxjs



i have created an example(listen for every second change) using StackBlitz : https://stackblitz.com/edit/angular-4ytdbs






share|improve this answer




















  • Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
    – MS_AU
    Nov 12 '18 at 23:35











  • @MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
    – CruelEngine
    Nov 13 '18 at 8:19










  • Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
    – MS_AU
    Nov 13 '18 at 10:59










  • @MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
    – CruelEngine
    Nov 13 '18 at 12:44













0












0








0






You can use a subject and interval for this i guess maybe some way like this :



Basically in your code where you have implemented this(assuming it is a separate service : some.service.ts ) , define a subject like this :



someSubject : Subject<Date> = new Subject<Date>();

interval(1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date =>
console.log(date);
this.someSubject.next(date);
);
).subscribe();


Subscribe to the someSubject from wherever you want to listen to the date change like this :



this._someService.someSubject.subscribe((date : Date) =>
console.log(date); //you'll have a new date object everytime your date object changes i.e everyminute
);


don't forget to import interval from rxjs



i have created an example(listen for every second change) using StackBlitz : https://stackblitz.com/edit/angular-4ytdbs






share|improve this answer












You can use a subject and interval for this i guess maybe some way like this :



Basically in your code where you have implemented this(assuming it is a separate service : some.service.ts ) , define a subject like this :



someSubject : Subject<Date> = new Subject<Date>();

interval(1000)
.pipe(
map(() => new Date()),
distinctUntilChanged((a: Date, b: Date) => a.getMinutes() === b.getMinutes()),
tap(date =>
console.log(date);
this.someSubject.next(date);
);
).subscribe();


Subscribe to the someSubject from wherever you want to listen to the date change like this :



this._someService.someSubject.subscribe((date : Date) =>
console.log(date); //you'll have a new date object everytime your date object changes i.e everyminute
);


don't forget to import interval from rxjs



i have created an example(listen for every second change) using StackBlitz : https://stackblitz.com/edit/angular-4ytdbs







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 12 '18 at 7:58









CruelEngine

9791919




9791919











  • Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
    – MS_AU
    Nov 12 '18 at 23:35











  • @MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
    – CruelEngine
    Nov 13 '18 at 8:19










  • Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
    – MS_AU
    Nov 13 '18 at 10:59










  • @MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
    – CruelEngine
    Nov 13 '18 at 12:44
















  • Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
    – MS_AU
    Nov 12 '18 at 23:35











  • @MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
    – CruelEngine
    Nov 13 '18 at 8:19










  • Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
    – MS_AU
    Nov 13 '18 at 10:59










  • @MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
    – CruelEngine
    Nov 13 '18 at 12:44















Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
– MS_AU
Nov 12 '18 at 23:35





Thanks for your example, however it is still triggering change detection every second. I'm trying to "defer change detection so it only occurs when a new value is emitted". So once per minute, rather than once per second. I have updated your example with what I have: stackblitz.com/edit/angular-jbay8g
– MS_AU
Nov 12 '18 at 23:35













@MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
– CruelEngine
Nov 13 '18 at 8:19




@MS_AU how is it triggering a change detection every second ? a timer or an interval emits an observable based on the value you've pushed
– CruelEngine
Nov 13 '18 at 8:19












Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
– MS_AU
Nov 13 '18 at 10:59




Angular's change detection is triggered in response to asynchronous tasks. In the case of a timer or interval Observable change detection will occur after the specified delay, every second (1000ms) in my case. Given I was piping the emitted values through a map and distinctUntilChanged operator - a new value is only emitted once per minute, not once per second. However, change detection still occurs every second. This question is specifically around the best practices for deferring change detection with Observable timers.
– MS_AU
Nov 13 '18 at 10:59












@MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
– CruelEngine
Nov 13 '18 at 12:44




@MS_AU you can reattach and detach the change detection using changeDetectionStrategy.detach() and changeDetectionStartegy.reattach() and also set changeDetectionStrategy to onPush . i have the plunker updated but it seems like ngDoCheck is called anyways which shouldn't be the case
– CruelEngine
Nov 13 '18 at 12:44

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254339%2fangular-change-detection-with-observable-timer%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo