KnowledgeSeeker001
KnowledgeSeeker001

Reputation: 638

how to subscribe to the last observable and execute a funtion in rxjs?

Hi I am having a small code snippet in my project .

it basically subscribe to an angular form group and calls a method generatePerformanceGraph that draws an svg.

the form group has around 6 form controls . the problem is some times when i change the value of a form control , it will set another values to another form controls. As a result when i change some form control value it causes generatePerformanceGraph to called multiple times . How can i prevent this problem .

in short basically what i want is when there is a change in form group ,I would like to subscribe to the last observable and then execute the generatePerformanceGraph once.

this.formGroup.valueChanges.subscribe(formValue => {
  if(this.formGroup.valid) {
    this.generatePerformanceGraph(formValue);
  }
});

I have tried the following how ever it didnt work out well.

this.formGroup.valueChanges.
pipe(
  distinctUntilChanged()
) .subscribe( formValue => {
  if(this.formGroup.valid) {
    this.generatePerformanceGraph(formValue);
  }
});

Upvotes: 0

Views: 353

Answers (1)

AliF50
AliF50

Reputation: 18809

Try debounceTime, the time is up to you in ms. The debounceTime ignores events that happen within 200ms of each other and only accept the last one.

https://www.learnrxjs.io/learn-rxjs/operators/filtering/debouncetime

this.formGroup.valueChanges.
pipe(
  debounceTime(200),
) .subscribe( formValue => {
  if(this.formGroup.valid) {
    this.generatePerformanceGraph(formValue);
  }
});

To go the distinctUntilChanged way, you have to do it a different way because formValue is an object.

this.formGroup.valueChanges.
pipe(
  distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
) .subscribe( formValue => {
  if(this.formGroup.valid) {
    this.generatePerformanceGraph(formValue);
  }
});

Upvotes: 1

Related Questions