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

时间:2017-07-05 12:49:04

标签: react-native redux-saga

我有一个用于监听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');
  }
}

1 个答案:

答案 0 :(得分:4)

自己回答..

我刚在文档中找到了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');
  }
}