Skip to content

[Feature request] debouncedSignal #595

@dzolotarova

Description

@dzolotarova

Hi!
I suggest adding a debouncedSignal function that creates a debounced signal from a source signal.

I have such an implementation:

import { Signal } from '@angular/core';
import { toObservable, toSignal, ToSignalOptions } from '@angular/core/rxjs-interop';
import { debounceTime } from 'rxjs';

export function debouncedSignal<T>(
  source: Signal<T>,
  debounceDelay: number,
  options?: NoInfer<ToSignalOptions<T | undefined>> & {
    initialValue?: undefined;
    requireSync?: false;
  },
): Signal<T | undefined>;
export function debouncedSignal<T>(
  source: Signal<T>,
  debounceDelay: number,
  options: NoInfer<ToSignalOptions<T | null>> & {
    initialValue?: null;
    requireSync?: false;
  },
): Signal<T | null>;
export function debouncedSignal<T>(
  source: Signal<T>,
  debounceDelay: number,
  options: NoInfer<ToSignalOptions<T>> & {
    initialValue?: undefined;
    requireSync: true;
  },
): Signal<T>;
export function debouncedSignal<T, const U extends T>(
  source: Signal<T>,
  debounceDelay: number,
  options: NoInfer<ToSignalOptions<T | U>> & {
    initialValue: U;
    requireSync?: false;
  },
): Signal<T | U>;
/**
 * Creates a debounced signal from a source signal.
 * The debounced signal will wait for a specified delay after the last change before updating its value.
 *
 * @param source - The source signal to debounce
 * @param debounceDelay - The delay in milliseconds to wait after the last change
 * @param options - Optional configuration for the signal conversion
 *
 * @returns A new signal that updates after the specified delay
 *
 * @example
 * ```ts
 * const search = signal('');
 * const debouncedSearch = debouncedSignal(search, 300);
 * ```
 */
export function debouncedSignal<T, U = undefined>(
  source: Signal<T>,
  debounceDelay: number,
  options?: ToSignalOptions<T | U> & { initialValue?: U },
): Signal<T | U> {
  const sourceWithDebounce$ = toObservable(source).pipe(debounceTime(debounceDelay));

  return toSignal(
    sourceWithDebounce$,
    options as ToSignalOptions<T | undefined> & {
      initialValue?: undefined;
      requireSync?: false;
    },
  ) as Signal<T | U>;
}

Usage:

const search = signal('');
const debouncedSearch = debouncedSignal(search, 300);

It can be useful. What do you think about it? I will be happy to create a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions