Skip to content

Instantly share code, notes, and snippets.

@nacmartin
Last active September 23, 2019 14:57
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 nacmartin/57a7584d4681ebf100c819416fa66400 to your computer and use it in GitHub Desktop.
Save nacmartin/57a7584d4681ebf100c819416fa66400 to your computer and use it in GitHub Desktop.
Before testing
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