bigpotato
bigpotato

Reputation: 27497

Redux Saga: How to call yield + put within a nested function?

I am using WebRTC with redux sagas. One requirement is that I have to define peerConnection.onicecandidate:

function* createPeerConnection(action) {
  ...
  peerConnection = new RTCPeerConnection(servers);

  peerConnection.onicecandidate = (event) => {
    if (event.candidate) {
      yield put({ type: videoSessionActions.SEND_LOCAL_CANDIDATE, payload: event.candidate });
    }
  }
}

However, yield put is not working in this method. How would I change this so that it works with sagas?

Upvotes: 2

Views: 890

Answers (1)

DraganS
DraganS

Reputation: 2699

Hope that the event channel can help you:

import { eventChannel, END } from 'redux-saga';
import { put, take } from 'redux-saga/effects';

import { videoSessionActions } from '../???/constants';

const rtcChannel = servers => eventChannel(emitter => {
  const peerConnection = new RTCPeerConnection(servers);
  peerConnection.onicecandidate = event => {
    if (event.candidate) {
      emitter({type: videoSessionActions.SEND_LOCAL_CANDIDATE, payload: event.candidate});
    }
  };
  return () => {
    peerConnection.close();
  };
}
// ,buffers.expanding(1024) ???
);

function* createPeerConnection(servers) {
  const ch = rtcChannel(servers);

  while(true) { // eslint-disable-line no-constant-condition
    const candidate = yield take(ch);
    yield put(candidate);
  }
}

Upvotes: 1

Related Questions