JS
S
JavaScript

Using RxJS constructs to build a 4s timer

1import { BehaviorSubject, Observable, timer } from 'rxjs';
2import { concatMap, distinctUntilChanged, map, mapTo, skip, startWith } from 'rxjs/operators';
3
4private readonly characterSubject$ = new BehaviorSubject<string>('');
5
6this.character$ = this.characterSubject$.asObservable();
7
8private readonly characterDebounceTime = 4000;
9
10    this.characterChange$ = this.character$.pipe(
11      distinctUntilChanged(),
12      untilDestroyed(this),
13    );
14
15    this.characterDisabled$ = this.characterChange$.pipe(
16      skip(1),
17      concatMap(() => (
18        timer(this.characterDebounceTime).pipe(
19          mapTo(false),
20          startWith(true),
21        )),
22      ),
23    );
24
25
26
27/* HTML
28    <input
29      type="text"
30      matInput
31      maxlength="1"
32      placeholder="Character"
33      [ngModel]="character$ | async"
34      (ngModelChange)="setCharacter($event)"
35      [disabled]="(characterDisabled$ | async) === true"
36    >
37*/
38
39
40
41// SetInterval
42
43// RxJS v6+
44import { interval } from 'rxjs';
45
46//emit value in sequence every 1 second
47const source = interval(1000);
48//output: 0,1,2,3,4,5....
49const subscribe = source.subscribe(val => console.log(val));

Created on 3/4/2020