pr0metheus
pr0metheus

Reputation: 488

How to get last value of observable by key using debounceTime

 employeeChanged: Subject<any> = new Subject<any>();
 setInterval(() => {
     this.employeeChanged.next(1);
     this.employeeChanged.next(1);
     this.employeeChanged.next(2);
     this.employeeChanged.next(2);
     this.employeeChanged.next(3);
     this.employeeChanged.next(3);
 },1000);

 this.employeeChanged.pipe(debounceTime(1000),distinctUntilChanged()).subscribe(((key) => {
            console.log(`Employee update: ${key}`);
 }));

My example looks like this. I want to get latest value by key that i provide to subject observable so my output looks like this

Employee update: 1
Employee update: 2
Employee update: 3

Which operator i need to use to achieve that?

Upvotes: 2

Views: 1445

Answers (1)

Tal Ohana
Tal Ohana

Reputation: 1138

Since you are using the same value for debounceTime and setInterval delay, the debounceTime time span won't pass and no values will be emitted.

Now, there are two options:

  1. Lowering debounceTime timer, but it will result in only dispatching the latest value since the debounce will ignore the close-emitted values
  2. Removing debounceTime operator and get your desired behavior

I assume you wanted some sort of delay between emissions, you can use bufferTime to collect the distincted values for some time span, then use mergeAll to flatten the collected values

employeeChanged
  .pipe(
    distinctUntilChanged(),
    bufferTime(1000),
    mergeAll()
  )
  .subscribe(key => {
    console.log(`Employee update: ${key}`);
  });

Upvotes: 2

Related Questions