1
votes

I'm iterating over a object array obtained from a service with 'NgFor'.

At first I updated the object array variable inside subscribe method, and I realize two things.

this._myService.sendRequest(input).subscribe((value: SomethingInterface[]) => {
    this.objectArray = value.map((v) => new Something(v))
});

First: (advantage) If I do a new request the old value is keeped until I receive a new value.

Second: (disadvantage) If I do multiples requests, they are put in a queue and each request is made consuming unnecessary bandwidth.

Then I moved to Async pipe, and realize another two things.

this.objectArrayObservable = this._myService.sendRequest(value: SomethingInterface[]).pipe(
    map((value) => value.map((v) => new ChartDisplayDOM(v)))
);

First: (advantage) If I do multiples requests the old are cancelled, and only the last request is made.

Second: (disadvantage) While waiting the request to complete, the array is empty...and I don't want to make a loading bar.

Is there a way to take both advantages?

If I do a new request the old value is keeped until I receive a new value.

If I do multiples requests the old are cancelled, and only the last request is made.

I tried some operators combinations like 'combineLatest' whith two differents Observables but I didn't figure out how to solve it.

1

1 Answers

1
votes

Instead of creating new chains on every user action make just one chain starting with an instance of Subject:

s = new Subject();

...

s.pipe(
  switchMap(input => this._myService.sendRequest(input)),
).subscribe((value: SomethingInterface[]) => {
  this.objectArray = value.map((v) => new Something(v))
});

...
// User does some action...
s.next(input);

switchMap() will make sure that if there was any pending requset it's going to be canceled. Just don't forget to unsubscribe when the component is being destroyed.