Debounce async validator

PHOTO EMBED

Fri Feb 24 2023 15:04:18 GMT+0000 (Coordinated Universal Time)

Saved by @mtommasi

const asyncValidator: AsyncValidatorFn = (control: AbstractControl) => {
    const email = control.value;

    const values$ = control.valueChanges;

    return values$.pipe(
      debounceTime(1000),
      distinctUntilChanged(),
      switchMap((value) => userService.userEmailExists(value)),
      map((exists) => {
        if (exists) {
          return { userExists: true };
        } else {
          return null;
        }
      }),
      first(),
      catchError((err) => {
        return NEVER; // non completa mai e resta in pending
      })
    );
  };
content_copyCOPY