Search code examples
angularrxjsobservablelong-pollingbehaviorsubject

Angular RXJS Long Poll


I have a backend that maintains a store for the frontend. with every hit I am returning the full store that includes an array of messages that should be rendered.

Fetching data from backend is via long poll implemented in a service.

The problem is: DOM not keep updating with every cll to the backend, I am trying to render the update only not the full array.

with the current implantation POM updates with every hit. Is there a way to solve it ??

I tried the following code:

In my html template:

<div *ngFor="let message of messages$ | async">
{{message}}
</div>

in the components ts file:

messages$ = storeService.messages;
ngOnInit(){
this.messages$.subscribe();
}

in Store Service:


  get messages(): Observable<any> {
    return this._messages.asObservable();
  }
 
  private _messages = new BehaviorSubject<any[]>([]);
 
  messages$ = this._messages.asObservable()

 storeGet$ = this.http.get(EndPoint)
getStore(){
return timer(0, 15000).pipe(
        concatMap(() => storeGet$),
        map(resp => {
 
          this._messages.next(resp['messages'])
        })
      )
}

Solution

  • All you need is

    messages$ = timer(0, 15000).pipe(
      switchMap(_ => this.http.get(EndPoint)),
      map(resp => resp['messages'])
    )