Stop a publisher from streaming

In this guide we will look at stopping publishers from streaming to a session.

You can stop publisher from streaming to the session by unmounting it (removing it from the parent OTSession component). For example, the following code stops publishing a stream after 30 seconds:

import React, {Component} from 'react';
import {View} from 'react-native';
import {OTSession, OTPublisher} from 'opentok-react-native';

class App extends Component {
  constructor(props) {
    super(props);
    this.apiKey = 'your-api-key';
    this.sessionId = 'valid-session-id';
    this.token = 'valid-token';
    this.publisherOptions = {
      publishCaptions: true,
      publishVideo: true,
      publishAudio: false,
    };
    this.state = {
      publishing: true,
    };
    this.publisherEventHandlers = {
      streamCreated: event => {
        setTimeout(
          function () {
            console.log(10);
            this.setState({publishing: false});
          }.bind(this),
          10000,
        );
      },
    };
  }

  render() {
    return (
      <View>
        <OTSession
          applicationId={this.apiKey}
          sessionId={this.sessionId}
          token={this.token}
          {this.state.publishing ? (
            <OTPublisher
              eventHandlers={this.publisherEventHandlers}
              ref={instance => {
                this.publisher = instance;
              }}
            />
          ) : null}
        </OTSession>
      </View>
    );
  }
}

export default App;

Note that you can individually stop sending video or audio (while still publishing).

Detecting when a published stream leaves a session

The OTPublisher object dispatches a streamDestroyed event when it stops streaming to the session:

<OTPublisher
  eventHandlers={{
    streamDestroyed: function() {
      console.log('The publisher stopped streaming.');
    },
  }}
/>