Long Poll in Angular 4

I need to make API calls to display the progress of something.

I created a service that does this every 1.5 seconds

Main component

private getProgress() { this.progressService.getExportProgress(this.type, this.details.RequestID); } 

Services.ts

 public getExportProgress(type: string, requestId: string) { Observable.interval(1500) .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId)) .map((data) => data.json().Data) .subscribe( (data) => { if (!data.InProgress) //Stop doing this api call }, error => this.handleError(error)); } 

The challenge works, but it continues to move. I want to stop making an API call when progress is complete ( if (!data.InProgress ), but I'm stuck on this.

How can I correctly discard this observable when if (!data.InProgress) ?

thanks

+5
source share
2 answers

You can use the takeWhile .

Here is the documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-takeWhile

It emits the values โ€‹โ€‹emitted by the source Observed if each value satisfies a given predicate and then completes as soon as this predicate is not executed.

Here is a general example: https://rxviz.com/v/yOE6Z5JA

 Rx.Observable .interval(100) .takeWhile(x => x < 10) .subscribe(x => { console.log(x); }); 

Here is an example with your code:

 public getExportProgress(type: string, requestId: string) { Observable.interval(1500) .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId)) .map((data) => data.json().Data) .takeWhile((data) => data.InProgress) .subscribe( (data) => { ... }, error => this.handleError(error)); } 
+5
source

I solved this by placing the service call in a variable and discarding this variable when done.

Here is the result:

 public getExportProgress(type: string, requestId: string): any { let progress = Observable.interval(1500) .switchMap(() => this.http.get(this.apiEndpoint + "Definition/" + type + "/Progress/" + requestId)) .map((data) => data.json().Data) .subscribe( (data) => { if (!data.InProgress) { this.toastyCommunicationService.addSuccesResponseToast("done"); progress.unsubscribe(); } }, error => this.handleError(error)); } 
+2
source

Source: https://habr.com/ru/post/1272593/


All Articles