gpt4 book ai didi

reactjs - React Redux Saga 事件 channel 取消

转载 作者:行者123 更新时间:2023-12-02 16:35:27 25 4
gpt4 key购买 nike

是否有任何可能的方法通过 Redux Saga 中的副作用来取消 eventChannel

假设有一个连接到外部事件/数据流的 eventChannel,在本例中为 Firebase 实时数据库 “child_added” 事件:

// action
const types = { SYNC: 'SYNC_TODOS' };
function syncTodos(todos) {
return { types: types.SYNC, todos }
}

// saga
function todosChannel() {
// firebase database ref
const ref = firebase.database().ref('todos/');

const channel = eventChannel(emit => {
const callback = ref.on('child_added', (data) => {
emit({ snapshot: data, value: data.val() })
});

// unsubscribe function
return () => ref.off('child_added', callback);
});

return channel;
}

function* sync() {
const channel = yield call(todosChannel);

try {
while (true) {
const { value } = yield take(todosChannel);
yield put(actions.syncTodos(value));
}
}
finally {
if(yield cancelled()) {
channel.close();
}
}
}

export default function* rootSaga() {
yield fork(sync);
}

是否有任何方法可以使用诸如 fork() 之类的副作用和 takeEvery() 之类的方法来监听取消事件 channel 并停止监听 Firebase “child_added” 事件的操作/数据流?或者这是否需要以某种方式保存对 channel 的引用并在 channel 引用本身上执行 cancel() ?

感谢您提供的任何帮助。

最佳答案

你是说这个吗?

function* sync() {
const channel = yield call(todosChannel);

yield takeEvery(channel, function*({value}){
yield put(actions.syncTodos(value))
}

yield take('CANCEL_WATCH')
channel.close();
}

顺便说一句,takeEvery是帮助者,而不是效果。

关于reactjs - React Redux Saga 事件 channel 取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46429081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com