Learn RxJS
Search…
Swipe To Refresh
By adamlubek
This recipe demonstrates RxJS implementation of swipe to refresh functionality. Inspired by @BenLesh RxJs talks.

Example Code

Could not load image
Swipe to Refresh

index.ts

1
// RxJS v6+
2
import { fromEvent, iif, of, pipe } from 'rxjs';
3
import {
4
finalize,
5
mergeMap,
6
takeUntil,
7
takeWhile,
8
repeat,
9
map,
10
tap,
11
exhaustMap,
12
delay
13
} from 'rxjs/operators';
14
15
const setRefreshPos = y =>
16
(document.getElementById('refresh').style.top = `${y}px`);
17
const resetRefresh = () => setRefreshPos(10);
18
const setData = data => (document.getElementById('data').innerText = data);
19
20
const fakeRequest = () =>
21
of(new Date().toUTCString()).pipe(
22
tap(_ => console.log('request')),
23
delay(1000)
24
);
25
26
const takeUntilMouseUpOrRefresh$ = pipe(
27
takeUntil(fromEvent(document, 'mouseup')),
28
takeWhile(y => y < 110)
29
);
30
const moveDot = y => of(y).pipe(tap(setRefreshPos));
31
const refresh$ = of({}).pipe(
32
tap(resetRefresh),
33
tap(e => setData('...refreshing...')),
34
exhaustMap(_ => fakeRequest()),
35
tap(setData)
36
);
37
38
fromEvent(document, 'mousedown')
39
.pipe(
40
mergeMap(_ => fromEvent(document, 'mousemove')),
41
map((e: MouseEvent) => e.clientY),
42
takeUntilMouseUpOrRefresh$,
43
finalize(resetRefresh),
44
exhaustMap(y => iif(() => y < 100, moveDot(y), refresh$)),
45
finalize(() => console.log('end')),
46
repeat()
47
)
48
.subscribe();
Copied!

html

1
<style>
2
#refresh {
3
position: absolute;
4
width: 20px;
5
height: 20px;
6
background: grey;
7
border-radius: 50%;
8
left: 50%;
9
}
10
11
#point {
12
position: absolute;
13
width: 10px;
14
height: 10px;
15
background: lightgrey;
16
border-radius: 50%;
17
left: 51%;
18
top: 105px;
19
}
20
21
#data {
22
position: absolute;
23
top: 150px;
24
}
25
</style>
26
27
<div id='refresh'></div>
28
<div id='point'></div>
29
<div id='data'>Swipe gray dot down to get latest date/time</div>
Copied!

Operators Used

Last modified 1yr ago