This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original code | |
const pingEpic = ( | |
action$, | |
) => ( | |
action$ | |
.pipe( | |
ofType(PING), | |
delay(1000), | |
map(pong), | |
) | |
) | |
// Accepted solution. | |
const pingEpic = ( | |
action$, | |
) => ( | |
action$ | |
.pipe( | |
ofType(PING), | |
switchMap(() => ( | |
timer(1000) | |
)), | |
map(pong), | |
) | |
) | |
// This kills the entire observable when another PING comes in. Not what you want. | |
const pingEpic = ( | |
action$, | |
) => ( | |
action$ | |
.pipe( | |
ofType(PING), | |
takeUntil( | |
action$ | |
.pipe( | |
ofType(PING) | |
) | |
), | |
delay(1000), | |
map(pong), | |
) | |
) | |
// Instead of using `switchMap`, you could use `takeUntil` and `mergeMap` just fine. | |
const pingEpic = ( | |
action$, | |
) => ( | |
action$ | |
.pipe( | |
ofType(PING), | |
mergeMap(() => ( | |
timer(1000) | |
.pipe( | |
takeUntil( | |
action$ | |
.pipe( | |
ofType(PING) | |
) | |
) | |
) | |
)), | |
map(pong), | |
) | |
) | |
// I use namespaces often for reusable epics and reducers (https://itnext.io/the-secret-to-using-redux-createnamespacereducer-d3fed2ccca4a) | |
// They comes in handy when you're using one epic for multiple uses. | |
const pingEpic = ( | |
action$, | |
) => ( | |
action$ | |
.pipe( | |
ofType(CREATE_PING_LISTENER) | |
mergeMap(({ | |
namespace, | |
}) => ( | |
action$ | |
.pipe( | |
ofType(PING), | |
ofNamespace(namespace), | |
takeUntil( | |
action$ | |
.pipe( | |
ofType(STOP_PING_LISTENER) | |
) | |
), | |
switchMap(() => ( | |
timer(1000) | |
)), | |
mapTo({ namespace }), | |
map(pong), | |
)), | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment