I need to update the data on the component page in one interval. I also need to update the data after performing some actions. I use Obeservables in the service so that I can subscribe when the answer is ready. I am pushing subscriptions to an object so that I can understand that on ngDestroy , I think I have the following methods to achieve the same.
Method 1: setInterval
I set the interval to ngOnInit , which will call refreshData in equal interval. The interval object will be cleared using the clearInterval method in ngOnDestroy .
export class MyComponent implements OnInit, OnDestroy { private subscription: Subscription = new Subscription(); data: any; interval: any; ngOnInit() { this.refreshData(); this.interval = setInterval(() => { this.refreshData(); }, 5000); } ngOnDestroy() { this.subscription.unsubscribe(); clearInterval(this.interval); } refreshData(){ this.subscription.add( this.myService.getData() .subscribe(data => { this.data = data; }) ); } doAction(){ this.subscription.add( this.myService.doAction() .subscribe(result => { if(result === true){ this.refreshData(); } }) ); } }
Q1: Each time the update is called, the subscription will be added to the subscription object, which will increase memory usage and may lead to browser crash if the user opens the page for some time?
Method2: Observable.timer
This method uses a timer that will be created after updating the data.
export class MyComponent implements OnInit, OnDestroy { private subscription: Subscription = new Subscription(); data: any; ngOnInit() { this.refreshData(); } ngOnDestroy() { this.subscription.unsubscribe(); } refreshData(){ this.subscription.add( this.myService.getData() .subscribe(data => { this.data = data; this.subscribeToData(); }) ); } subscribeToData(){ this.subscription.add( Observable.timer(10000).subscribe(() => this.refreshData()) ); } doAction(){ this.subscription.add( this.myService.doAction() .subscribe(result => { if(result === true){ this.refreshData(); } }) ); } }
Q2: I have the same question (Q1) here. Thus, timers are also added to the subscription object, so in fact the subscriptions in the subscription object are doubled.
Q3: To update the data after the action method - doAction (), refreshData is called. So will this create another timer chain?
Q4: What is the best way without memory leaks or if there is any other way?
source share