Ravi Khambhati
Ravi Khambhati

Reputation: 743

take() with debounceTime() takes the last element only

I am new to RxJS and have a doubt.

Below code works fine and prints 'Robert" and 'Mark'

    let studentNames = ['Robert','Mark','Sam'];
    from(studentNames).pipe(take(2)).subscribe(
      data => 
      {
        console.log(data);
      });

But when I added debounceTime it only prints 'Mark'. Why is this?

    let studentNames = ['Robert','Mark','Sam'];
    from(studentNames).pipe(take(2),debounceTime(1000)).subscribe(
      data => 
      {
        console.log(data);
      });

Upvotes: 2

Views: 1103

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

From the Docs of debounceTime:

Emits a notification from the source Observable only after a particular time span has passed without another source emission.

In your case, your source emits two values without any time in-between. debounceTime will then wait 1000ms after the last emission is received and emit it.

The order of your operators within the pipe matters. Notice that if you put debounceTime before take you will see different behavior; only "Sam" would be emitted. This is because debounceTime would receive all three emissions, then only emit the final one after the 1000ms has passed. The take(2) wouldn't even come into play because the source (from) would complete before the take received two emissions.

Upvotes: 3

Related Questions