Skip to content

Instantly share code, notes, and snippets.

@alexmnv
Last active March 20, 2022 21:04
Show Gist options
  • Save alexmnv/e72631e7f5182c94a62a1277c968964b to your computer and use it in GitHub Desktop.
Save alexmnv/e72631e7f5182c94a62a1277c968964b to your computer and use it in GitHub Desktop.
redux-saga - runSaga() example with custom IO, using node.js EventEmitter
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)
@alexmnv
Copy link
Author

alexmnv commented Dec 14, 2017

As of 0.15.0 runSaga's first argument should be IO interface. So the code should be

runSaga(
  createSagaIO(emitter, () => state),
  helloSaga
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment