React Redux Saga 事件通道取消

React Redux Saga Event Channel Cancel

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

给定 eventChannel 连接到外部 event/data 流,在本例中为 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() 之类的东西来监听取消事件通道并停止监听 Firebase 的操作 "child_added" event/data 溪流?或者这是否需要以某种方式保存对通道的引用并在通道引用本身上执行 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 是助手,不是效果。

我不得不稍微修改接受的答案方法以捕获我的频道中发出的错误。我也更喜欢在分叉中处理取消,而不是像接受的答案中那样分叉处理值。

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))
  }
}