有没有办法在WebSocketSubject上获得重新连接事件?

时间:2018-04-01 10:34:01

标签: websocket rxjs

我尝试使用WebSocketSubject,并在连接中断时实现重新连接。我尝试使用提供的钩子(openObserver,closeObserver等)。当我关闭网络连接时,不会调用观察者,并且在retryWhen中没有日志输出。

我的代码是这样的:

let open
const openObservable = rx.Observable.create(observer => open = observer)
openObservable.subscribe((m: OpenEvent) => console.error('open observer'))

let close
const closeObservable = rx.Observable.create(observer => close = observer)
closeObservable.subscribe((m: OpenEvent) => console.error('close observer', m))

let closing
const closingObservable = rx.Observable.create(observer => closing = observer)
closingObservable.subscribe((m: OpenEvent) => console.error('closing observer', m))

this.ws$ = rx.Observable.webSocket({
  url: 'ws://example.com/ws,
  WebSocketCtor: WebSocket,
  openObserver: open,
  closeObserver: close,
  closingObserver: closing,
})
  .retryWhen(errors => {
    logger.warn('Connection error!')

    return errors.delayWhen(() => rx.Observable.timer(Math.pow(2, 1)))
  })
 .subscribe(m => doStuff(m))

我的问题:

  • 观察员是否应该工作,并用于此用例?
  • 我的方法是否正确?

环境:

  • 的Linux
  • NodeJS 9
  • WebSocket(ws library v5)
  • rxjs 5

0 个答案:

没有答案