当某个动作发生时如何关闭 eventChannel

Mic*_*ael 2 react-native redux-saga

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

我还想听一个动作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');
  }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 5

我自己回答这个..

我刚刚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');
  }
}
Run Code Online (Sandbox Code Playgroud)