How would I combine the results from two Observables but also use result of one observable if it returns sooner than the other?

Viewed 163

I have two observable objects returned from Angular 8 services. One gets column definitions for my grid and the other gets my grid data. I'm using Ag-grid bound to two component properties for row data and column definitions.

I need both of these data sets to figure out the latest date in each column. The grid data always takes much longer to return than the column definition. Column definitions are almost instant. Grid data takes about 10 seconds.

Currently I use forkjoin to wait until both observables return their data. Then I set the bound properties. While this works, I want to update my column definitions as soon as they're available. Users think the grid looks like it's broken until the column definitions are populated.

Can I reuse the result of the column definition observable without calling the observable a second time?

Here's what my code looks like

let gridDataObservable= this.gridDataService.getItems();
let columnDefinitionObservable = this.columnDefinitionService.getItems();

forkJoin([gridDataObservable,columnDefinitionObservable]).subscribe(results => {
  this.rowData= results[0];
  this.columnDefs = results[1];
  this.latestDates = GetDates(this.rowData,this.columnDefs);
}
2 Answers

Since it sounds like both of your observables are one-shots, I think that the easiest thing would be to not combine them. Just subscribe to each individually.

const columnDefinitionObservable = this.columnDefinitionService.getItems();

const gridDataSubject = new BehaviorSubject<YourType|undefined>(undefined);
this.gridDataService.getItems().subscribe(gridDataSubject)

const target$ = combineLatest(columnDefinitionObservable, gridDataSubject)

Give a undefined initial value for gridData. If columnDefinitionObservable fires first, you will get [column, undefined], then [column, gridData]

If the gridData fires first, you will get [column, gridData] directly.

Related