title: How to debounce async validator in Angular 4 with RxJS observable?
body: <p>I'm using custom async validator with Angular 4 reactive forms to check if E-Mail address is already taken by calling a backend.</p>
  
  <p>However, Angular calls the validator, which makes request to the server for every entered character. This creates an unnecessary stress on the server.</p>
  
  <p>Is it possible to elegantly debounce async calls using RxJS observable?</p>
  
  <pre class="lang-typescript prettyprint-override"><code>import {Observable} from 'rxjs/Observable';
  
  import {AbstractControl, ValidationErrors} from '@angular/forms';
  import {Injectable} from '@angular/core';
  
  import {UsersRepository} from '../repositories/users.repository';
  
  
  @Injectable()
  export class DuplicateEmailValidator {
  
    constructor (private usersRepository: UsersRepository) {
    }
  
    validate (control: AbstractControl): Observable&lt;ValidationErrors&gt; {
      const email = control.value;
      return this.usersRepository
        .emailExists(email)
        .map(result =&gt; (result ? { duplicateEmail: true } : null))
      ;
    }
  
  }
  </code></pre>