我想通过按钮启动和停止eventSource。使用CONSTANTS.FETCHING_STOPPED操作的CONSTANTS.FETCHING_STARTED操作和停止按钮的开始按钮。
https://github.com/redux-saga/redux-saga/issues/940 - 不适合我。
我试过停止并启动一个功能,但它没有用。
这是我的传奇。
import {
call,
take,
takeLatest,
put,
race,
cancelled
} from "redux-saga/effects";
import { eventChannel, END } from "redux-saga";
import * as CONSTANTS from "../constants";
export function* innerSSE(eventSrc) {
const eCh = eventChannel(emitter => {
eventSrc.onmessage = msg => {
emitter(msg);
};
eventSrc.onerror = () => {
emitter(END);
};
return () => {
eventSrc.close();
};
});
try {
yield takeLatest(eCh);
} finally {
if (yield cancelled()) eCh.close();
}
}
function* start() {
const eventSrc = new EventSource(CONSTANTS.STREAM_URL);
const chan = yield call(innerSSE, eventSrc);
while (true) {
const msg = yield take(chan);
yield put({
type: CONSTANTS.FETCHING_IN_PROGRESS,
payload: JSON.parse(msg.data)
});
}
}
function* stop(eventSrc) {
// innerSSE.close()
}
export function* sseSaga() {
while (true) {
try {
const started = yield take(CONSTANTS.FETCHING_STARTED);
yield call(start, started);
} catch (error) {
console.log(error);
}
}
}
qazxsw poi => dispatch action => saga trigger
试试这个
componentWillUnMount()
function* main(){
yield takeLatest(CONSTANTS.FETCHING_STARTED, function*(){
// create event channel
const chan = eventChannel(()=>{ /* ... */})
yield takeEvery(chan, function*(){
// process event
})
try{
// waiting for FETCHING_STOPPED
yield take(CONSTANTS.FETCHING_STOPPED)
}finally{
// or close by another FETCHING_STARTED
chan.close()
}
})
}