Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and debounce observable?

Tags:

rxjs

I have an observable that emits an object which contains a few params. In the object, one of the params (called optionId) distinctly identifies an option. I'd like to debounce all instances of that emission. However, if a new optionId shows up, I'd like to start a new clock, and start a new debounce.

Here's a sample marble diagram for what i'm looking for:

-----1----1-----1----3----3----3----3-----1---3---1---3---1------>
(magic operators for which I'm unclear)
-------------------1-------------------3-----1---3---1---3---1--->

I have debounce, which I like, but it does this:

-----1----1-----1----3----3----3----3-----1---3---1---3---1------>
debounce
-------------------1-------------------3--------------------1---->

It would skip all those intermediate 3s at the end... does this make sense?

like image 969
RandallB Avatar asked Mar 10 '26 16:03

RandallB


1 Answers

I think you're looking for this:

source$.pipe(
  groupBy(item => item.optionId),
  map(group => group.pipe(
    debounceTime(1000),
  )),
  mergeAll(),
).subscribe(console.log);

What this does is that it groups the source into a higher order observable based on optionId, which gives you an observable per group. Each group is then separately mapped to a debounced version and in the end we merge it all back together.

It's one of those rare cases where using map to return an observable is actually what we want. :-)

like image 173
Ingo Bürk Avatar answered Mar 17 '26 11:03

Ingo Bürk