Skip to content

Instantly share code, notes, and snippets.

@dance2die
Last active October 19, 2019 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/3eecf3ac350c6470ab64078bb6b1e783 to your computer and use it in GitHub Desktop.
Save dance2die/3eecf3ac350c6470ab64078bb6b1e783 to your computer and use it in GitHub Desktop.
// 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