Last active
September 23, 2019 14:57
-
-
Save nacmartin/57a7584d4681ebf100c819416fa66400 to your computer and use it in GitHub Desktop.
Before testing
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
import * as effects from "redux-saga/effects"; | |
import { END, eventChannel } from "redux-saga"; | |
import * as constants from "../actions/constants"; | |
import io from "socket.io-client"; | |
export function* processTaskTimeConsuming() { | |
yield effects.delay(3000 + 1000 * Math.random()); | |
} | |
function* doProcessTask(name) { | |
try { | |
yield effects.put({ type: constants.TASK_PROCESS_START, name }); | |
yield effects.call(processTaskTimeConsuming); | |
yield effects.put({ type: constants.TASK_PROCESS_DONE, name }); | |
} catch (error) { | |
yield effects.put({ type: constants.TASK_PROCESS_ERROR, name }); | |
} finally { | |
if (yield effects.cancelled()) { | |
yield effects.put({ type: constants.TASK_PROCESS_RESET, name }); | |
} | |
return true; | |
} | |
} | |
export function* processTask(action) { | |
yield effects.call(doProcessTask, action.name); | |
} | |
function* wsEmitter() { | |
//const io = yield effects.getContext("io"); | |
const socket = yield effects.call(io, "http://localhost:3001"); | |
return eventChannel(emitter => { | |
socket.on("disconnect", reason => { | |
emitter(END); | |
socket.close(); | |
}); | |
socket.on("message", event => emitter(event)); | |
// The subscriber must return an unsubscribe function | |
return () => { | |
socket.close(); | |
}; | |
}); | |
} | |
export function* wsHandler() { | |
const wsChan = yield effects.call(wsEmitter); | |
while (true) { | |
const event = yield effects.take(wsChan); | |
if (event.type === "create") { | |
yield effects.put({ type: constants.TASK_CREATE, name: event.name }); | |
} | |
} | |
} | |
export function* rootSaga() { | |
yield effects.takeEvery(constants.TASK_PROCESS, processTask); | |
yield effects.fork(wsHandler); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment