简体   繁体   中英

Why does socket.io-client not connect inside of an RXJS subscription?

I am trying to initiate a socket.io connection upon receiving a certain event in an rxjs observable. The socket.io connection starts fine inside startEventStream if it's outside of the subscribe, but when placed in the subscribe, even though the event is firing, the callback inside socket is never called.

function startEventStream(
  stateLoaded$: Observable<LoginEvent>
): Observable<AoEvent> {
  const socket = require('socket.io-client')('http://localhost:8003')
  const ret = new Subject<AoEvent>()
  const merged = merge(stateLoaded$, ret)

  const session = '895e17a0-6c2b-11ea-8d86-45f581e4b250'
  const token =
    'f3ccdd81c2ece391891cba4f7d4eb8466d3d44675dd70f11e21190ae13dfdf69'
  merged.subscribe({
    next(val) {
      process.nextTick(() => {
        if (val.type == 'state-loaded') {
          console.log('we should be connecting')  // this prints
          socket.on('connect', function() {
            console.log('connected') // this doesn't print
            ret.next({ type: 'socket-connected' })
            socket.emit('authentication', {
              session,
              token
            })
          })
        }
      })
    }
  })
  return ret
}

I got it working by passing { autoconnect: false } into the initialization of the socket and doing socket.on() inside of the subscribe. I think the connect event was getting discarded before the subscription function was called, and so the callback was never firing. Starting the connection inside solves the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM