RxJS WebSocketSubject自定义握手

时间:2019-03-08 00:40:12

标签: rxjs

我正在尝试使用RxJS WebSocketSubject复用WebSocket连接以订阅多个通道。问题是我正在尝试遵循Bayeux协议,并且在WebSocketSubject发送订阅消息之前,没有明确的方法来发送额外的握手/连接数据。我入侵了观察程序以发送更多数据,但我需要一种从服务器获取响应的方法,以便可以在订阅消息中使用返回的clientid。为此,我破解了map方法,以便在它返回下一个动作之前先做一些工作,但是现在我认为必须有更好的方法。到目前为止,这是我的代码:

import { webSocket } from 'rxjs/webSocket';
import { filter, mergeMap, map } from 'rxjs/operators'

var assignedClientID = '';

const socket$ = webSocket({
  url: 'wss://sn-62092.local/bayeux/websocket',
  openObserver: {
    next: (e) => {
      e.target.send(JSON.stringify([{
        channel: '/meta/handshake',
        version: '1.0',
        supportedConnectionTypes: ['websocket']
      }]));
      e.target.send(JSON.stringify([{
        channel: '/meta/connect',
        clientId: assignedClientID,
        connectionType: 'websocket'
      }]));
    }
  },
});

export const bayeuxWebsocket = (action$, store) =>
  action$.pipe(
    filter(action => action.type === 'BAYEUX_SUBSCRIBE'),
    mergeMap(action =>
      socket$.multiplex(
        () => ([{
          channel: '/meta/subscribe',
          clientId: assignedClientID,
          subscription: action.subscription,
        }]),
        () => ([{
          channel: '/meta/unsubscribe',
          clientId: assignedClientID,
          subscription: action.subscription,
        }]),
        message => message
      ).pipe(
        map(data => {
          switch (data.channel) {
            case "/meta/handshake":
              assignedClientID = data.clientId;
              break;
            default:
              break;
          }
          return {type: 'NEXT_ACTION'}
        })
      )
    )
  );

0 个答案:

没有答案