-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
index.js
61 lines (55 loc) · 1.64 KB
/
index.js
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
55
56
57
58
59
60
61
/* eslint-disable no-constant-condition */
import { take, put, call, fork, race, cancelled } from 'redux-saga/effects'
import { eventChannel, END } from 'redux-saga'
import { INCREMENT_ASYNC, INCREMENT, CANCEL_INCREMENT_ASYNC, COUNTDOWN_TERMINATED } from '../actionTypes'
const action = type => ({ type })
/*eslint-disable no-console*/
export const countdown = secs => {
console.log('countdown', secs)
return eventChannel(listener => {
const iv = setInterval(() => {
secs -= 1
console.log('countdown', secs)
if (secs > 0) listener(secs)
else {
listener(END)
clearInterval(iv)
console.log('countdown terminated')
}
}, 1000)
return () => {
clearInterval(iv)
console.log('countdown cancelled')
}
})
}
export function* incrementAsync({ value }) {
const chan = yield call(countdown, value)
try {
while (true) {
let seconds = yield take(chan)
yield put({ type: INCREMENT_ASYNC, value: seconds })
}
} finally {
if (!(yield cancelled())) {
yield put(action(INCREMENT))
yield put(action(COUNTDOWN_TERMINATED))
}
chan.close()
}
}
export function* watchIncrementAsync() {
try {
while (true) {
const action = yield take(INCREMENT_ASYNC)
// starts a 'Race' between an async increment and a user cancel action
// if user cancel action wins, the incrementAsync will be cancelled automatically
yield race([call(incrementAsync, action), take(CANCEL_INCREMENT_ASYNC)])
}
} finally {
console.log('watchIncrementAsync terminated')
}
}
export default function* rootSaga() {
yield fork(watchIncrementAsync)
}