2
 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?

1 Answer 1

2

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}`);
  });
1
  • To be more precisely, my example with interval just simulate scenario, when i get information from socket to update data inside my frontend application. Problem with this is that socket sometimes send data to fast and with the same key, so i need take last value of current key in period time for example 500ms. Your solution not gonna work, because distinctUntilChanged prevent next update with the same key. I should write this in my question, but now i think you understand my problem. Thanks anyway :)
    – pr0metheus
    Jan 18, 2020 at 8:10

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.