-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
54 lines (40 loc) · 1.61 KB
/
Copy pathindex.ts
File metadata and controls
54 lines (40 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// https://github.com/seognil-study/learning-by-doing/tree/master/rxjs/save-indicator
// https://stackblitz.com/edit/rxjslc-save-indicator
// * ================================================================================
import { format } from 'date-fns';
import { concat, from, fromEvent, of } from 'rxjs';
import { debounceTime, delay, distinctUntilChanged, exhaustMap, map } from 'rxjs/operators';
// * ---------------------------------------------------------------- data and helper
const $input = document.getElementById('note-input');
const $saveIndicator = document.querySelector('.save-indicator');
const setInfo = (status) => {
$saveIndicator.innerHTML = status;
};
const getStamp = () => format(Date.now(), 'yyyy/MM/dd hh:mm');
const mockSave = (val) =>
new Promise((res, rej) => {
console.warn('called, should save: ', val);
// mockLocalStorageSave(val);
setTimeout(() => {
res('200');
}, ~~(Math.random() * 1000) + 1000);
});
// * ---------------------------------------------------------------- event logic
// * -------------------------------- input
const inputStream$ = fromEvent($input, 'input').pipe(
debounceTime(200),
map((e) => (e.target as HTMLInputElement).value),
distinctUntilChanged(),
);
// * -------------------------------- save action
const indecator$ = inputStream$.pipe(
exhaustMap((val) =>
concat(
of('Saving'),
from(mockSave(val)).pipe(map((code) => (code === '200' ? 'Saved' : 'Error'))),
of('Last Saved: ' + getStamp()).pipe(delay(1000)),
),
),
);
// * -------------------------------- subscribe
indecator$.subscribe(setInfo);