当某个动作出现时如何关闭 eventChannel

How to close an eventChannel when a certain action comes along

我有一个用于监听 webSockets 的 eventChannel,它工作正常。

我也想听一个动作USER_LOGGED_OUT然后关闭频道

如果出现套接字错误或套接字关闭,我将通过发出 END 从通道内关闭通道,但我如何根据外部操作执行此操作?

这是频道循环:

export function* websocketWatcher() {
  const tokenResponse = yield take(RECEIVE_USER_TOKEN);
  const accessToken = tokenResponse.payload.data.access_token;

  const channel = yield call(createWebsocketChannel, accessToken);
  try {
    while (true) {
      const action = yield take(channel);
      yield put(action);
    }
  } finally {
    console.log('Websocket channel terminated');
  }
}

我自己回答这个..

我刚在文档中找到 channel.close()。不知道我是怎么错过的。我通过通道(传入套接字数据)和注销操作之间的竞争解决了这个问题。

export function* websocketWatcher() {
  const tokenResponse = yield take(RECEIVE_USER_TOKEN);
  const accessToken = tokenResponse.payload.data.access_token;

  const channel = yield call(createWebsocketChannel, accessToken);
  try {
    while (true) {
      const { logoutAction, socketAction } = yield race({
        logoutAction: take(USER_LOGGED_OUT),
        socketAction: take(channel)
      });

      if (logoutAction) {
        channel.close();
      } else {
        yield put(socketAction);
      }
    }
  } finally {
    console.log('Websocket channel terminated');
  }
}