Search code examples
rxjsdebouncing

debounceTime only after first value


Is there a simple way to make debounceTime instant on the first value?

searchQueries.pipe(debounceTime(1000))

let's say i'm debouncing search queries to 1 second.

My understanding is that this will cause a 1 second delay on the first search, But, I want the first search query to be instant.

(e.g. in this example https://stackblitz.com/edit/typescript-adheqt?file=index.ts&devtoolsheight=50 if i type 123 quickly, it will only log 123, but i want it to log 1 and then log 123)

i could try something like

merge(searchQueries.pipe(first()),searchQueries.pipe(debounceTime(1000)))

but then that would potentially add a delay to a second search but is probably good enough.

Is there a way of configuring debounceTime that i'm missing? or should I potentially be using throttle or something else?


Solution

  • Here's my 2 cents / an answer I modified from another post with java-ngrx.

    dbounce-time-after.ts

    import { OperatorFunction, SchedulerLike, concat } from "rxjs";
    import { async } from "rxjs/internal/scheduler/async";
    import { debounceTime, publish, take } from "rxjs/operators";
    
    export function debounceTimeAfter(
      amount: number,
      dueTime: number,
      scheduler: SchedulerLike = async,
    ): OperatorFunction<number, number> {
      return publish(value =>
        concat(
          value.pipe(take(amount)),
          value.pipe(debounceTime(dueTime, scheduler))),
        )
      );
    }
    
    export function debounceTimeAfterFirst(
      dueTime: number,
      scheduler: SchedulerLike = async,
    ): OperatorFunction<number, number> {
      return debounceTimeAfter(1, dueTime, scheduler);
    }
    

    example.ts

    of(1, 2, 3, 4, 5)
      .pipe(
        tap(value => console.log("TAP", value)),
        debounceTimeAfterFirst(50)
      )
      .subscribe(value => console.log(value));
    

    console

    TAP 1
    1
    TAP 2
    TAP 3
    TAP 4
    TAP 5
    5
    

    But you could also start debouncing after n number of emits with debounceTimeAfter.