opentok / opentok-react

React components for OpenTok.js
https://www.npmjs.com/package/opentok-react
MIT License
107 stars 105 forks source link

Subscriber's events are not handle when reconnecting to a stream #146

Open HaleXie opened 4 years ago

HaleXie commented 4 years ago

https://github.com/opentok/opentok-react/blob/02ed7bcfe1db3c456c51f4841ea2bfc4c3d6c335/src/OTSubscriber.js#L122

If we want to reconnect, we might trigger these lines. The old subscriber instance is destroyed and a new instance is created

 componentDidUpdate()
...
    if (prevState.session !== this.state.session || prevState.stream !== this.state.stream) {
      this.destroySubscriber(prevState.session);
      this.createSubscriber();
    }
...

Here is the problem

  destroySubscriber(session = this.props.session) {
...
        this.state.subscriber.once('destroyed', () => {
         // This function might be executed after a new subscriber is created. 
        // So this.state.subscriber is NOT the old subscriber instance and this line removes all event handlers from the new subscriber instance
          this.state.subscriber.off(this.props.eventHandlers);
        });
      }
...

I apply this patch to fix the issue

  OTDestroySubscriber (session) {
    // This function provides a patch the event handlers are removed from the new subscriber
    session = session || this.props.session;
    delete this.subscriberId;
    const subscriber = this.state.subscriber;
    if (subscriber) {
      if (this.props.eventHandlers &&
        typeof this.props.eventHandlers === 'object') {
        subscriber.once('destroyed', () => {
          subscriber.off(this.props.eventHandlers);
        });
      }

      if (session) {
        session.unsubscribe(subscriber);
      }
    }
  }