Last active
March 20, 2022 21:04
-
-
Save alexmnv/e72631e7f5182c94a62a1277c968964b to your computer and use it in GitHub Desktop.
redux-saga - runSaga() example with custom IO, using node.js EventEmitter
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
const { runSaga } = require('redux-saga') | |
const { takeEvery, select } = require('redux-saga/effects') | |
const EventEmitter = require('events').EventEmitter | |
// | |
// Create Saga IO: | |
// | |
const createSagaIO = (emitter, getStateResolve) => ({ | |
// this will be used to resolve take Effects | |
subscribe: (callback) => { | |
// subscribe | |
emitter.on('action', callback) | |
// return unsubscibe function | |
return () => { | |
emitter.removeListener('action', callback) | |
} | |
}, | |
// this will be used to resolve put Effects | |
dispatch: (output) => { emitter.emit('action', output) }, | |
// this will be used to resolve select Effects | |
getState: getStateResolve | |
}) | |
// | |
// Usage example: | |
// | |
let emitter = new EventEmitter() | |
function* helloSaga() { | |
let s = yield select() | |
console.log('state', s) | |
yield takeEvery('message', (action) => { console.log(action.text) }) | |
} | |
const state = {} | |
runSaga( | |
helloSaga(), | |
createSagaIO(emitter, () => state) | |
) | |
setInterval(() => { | |
emitter.emit('action', {type: 'message', text: 'hello'}) | |
}, 500) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As of 0.15.0
runSaga
's first argument should be IO interface. So the code should be