Suppose I want to pull data from a backend every 15 seconds. Now my code is as follows:
TestComponent:
public ngOnInit(): void {
Observable.timer(0, 15000).subscribe(() => {
this.callService();
});
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
});
}
TestService:
public callBackendSerivce(): Subscribable<Data> {
return this.http.get(this.serviceUrl)
.map(this.extractData)
.catch(this.handleError);
}
The problem is that if some error occurs in the backend and the processing time takes more than 15 seconds, this code will hit the backend service again and will not wait for an answer again. I want to prevent this behavior and call the service only when I received a response from a previous call. How to implement this?
I thought it should look like this:
TestComponent:
public ngOnInit(): void {
this.callService();
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
this.subscribeToService();
});
}
private subscribeToService(): void {
this.timerSubscription= Observable.timer(15000).subscribe(() => {
this.callService();
this.timerSubscription.unsubscribe();
});
}
Two questions:
- Is there a better solution for this?
If not, does Observable.timer have a method to get the first result and automatically unsubscribe? This will prevent the addition of this code:
this.timerSubscription.unsubscribe ();