norty
norty

Reputation: 237

Update Items in Observable Array with RxJS

i have implemented an angular app which requests a list of items to fill a table. In my service i have the following function which requests the list of items from the server:

requestPostingList(): Observable<Posting[]> 

In the view the table subscribes to this Observable.

Dependig on a state variable in the Posting-Model I want poll the server for changes and update some (not all) items in the Posting[]. For that reason I have this function in my service class:

pollPostingState(postingId: string): Observable<Posting>

It polls every 2 secs on the server and if the state variable changes it emits a new Posting Object.

I need some kind of "merge mechanism" to update the items of the Posting[]. And this has to be done async, so I don't want to wait for all polls to finish. Every time a poll request finishes I want that in the UI, the corresponding row changes/updates. So I need to emit an updated Posting[]....

How can I achieve this with RXJS?

thanks in advance

Edit: How the table gets the data:

public dataSource = new MatTableDataSource<Posting>([]);

public ngAfterViewInit(): void {
this.postingService.requestPostingList()
    .subscribe(data => this.dataSource.data = data);
}

And in the HTML I bind dataSource to the mat-table

Upvotes: 0

Views: 661

Answers (1)

Rafael Andrade
Rafael Andrade

Reputation: 505

I don't know how your application is defined. But you can use the pipe with map function. Could be something like this:

myService.pollPostingState(id)
    .pipe(
        map( response : Posting ) => {
            updateArray(response)
            return response;
        }
    ).subscribe(...)

This change will trigger updateArray() every time a new request is made to pollPostingState with a valid return.

Upvotes: 1

Related Questions