Reactjs React Redux Saga事件通道取消

Reactjs React Redux Saga事件通道取消,reactjs,redux,redux-saga,Reactjs,Redux,Redux Saga,有没有可能通过Redux传奇中的副作用之类的东西来取消一个游戏 给定连接到外部事件/数据流的eventChannel,在这种情况下,Firebase实时数据库“添加的子事件”事件: // action const types = { SYNC: 'SYNC_TODOS' }; function syncTodos(todos) { return { types: types.SYNC, todos } } // saga function todosChannel() { // f

有没有可能通过Redux传奇中的副作用之类的东西来取消一个游戏

给定连接到外部事件/数据流的
eventChannel
,在这种情况下,Firebase实时数据库
“添加的子事件”
事件:

// 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()等)来侦听取消事件通道并停止侦听Firebase
“添加的孩子”
事件/数据流的操作?或者这是否需要以某种方式保存对通道的引用,并对通道引用本身执行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
是助手,而不是效果。

我不得不稍微修改接受答案的方法,以捕捉我频道中发出的错误。我也更喜欢在fork中处理cancel,而不是像在接受的答案中那样用fork来处理值

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

  yield fork(function* () {
    yield take('CANCEL_WATCH')
    channel.close();
  })

  try {
    while (true) {
      const { value } = yield take(channel)
      yield put(actions.syncTodos(value))
    }
  }
  catch (error) {
    yield put(actions.cancelWatch()) // to emit 'CANCEL_WATCH'
    yield put(actions.errorTodos(error))
  }
}

那真的很干净,谢谢!如果我想有条件地执行频道创建,我可以简单地在
收益调用(todosChannel)
之前放置一个
yield-take('SOME_-ACITON')
?alex:是的,
take
是阻塞效应。在看到这一点之前,我一生都在忍受恶心的
(true)