Redux Observable:如何从回调中返回一个动作?

时间:2017-05-09 06:21:51

标签: rxjs redux-observable

我正在使用具有非常特定API的WebRTC库。 peerConnection.setRemoteDescription方法的第二个参数应该是完成设置远程描述时的回调:

这是我的WebRTC类的包装函数之一:

export function setRemoteSdp(peerConnection, sdp, callback) {
  if (!sdp) return;
  return peerConnection.setRemoteDescription(
    new RTCSessionDescription(sdp),
    callback, // <-------------
  );
}

这是我想要做的草图:

function receivedSdp(action$, store) {
  return action$.ofType(VideoStream.RECEIVED_SDP)
    .mergeMap(action => {
      const {peerConnection} = store.getState().videoStreams;
      const {sdp} = action.payload;

      return WebRTC.setRemoteSdp(peerConnection, sdp, () => {
        return myReducer.myAction(); // <------ return action as the callback
      })
    })
};

这不起作用,因为我没有返回Observable。有没有办法做到这一点?

P.S。这是WebRTC API:https://github.com/oney/react-native-webrtc/blob/master/RTCPeerConnection.js#L176

2 个答案:

答案 0 :(得分:3)

所以问题是myReducer.myAction()Observable.create做的时候没有返回Observable,那是你要合并的Observable吗?

您可以使用WebRTC.setRemoteSdp并打包.mergeMap(action => { return Observable.create(observer => { WebRTC.setRemoteSdp(peerConnection, sdp, () => { observer.next(myReducer.myAction()); observer.complete(); }) }); } .mergeAll() 来电:

Observable.create

myReducer.myAction()返回一个Observable,它从mergeAll()发出另一个Observable。事实上,我实际上所谓的高阶,我希望使用concatAll展平({{1}}也可以。)

答案 1 :(得分:3)

马丁的回答是正确的,使用Observable.createnew Observable - 同样的事情(除了我不清楚为什么你需要mergeAll(),因为mergeMap会变平? )

作为奖励,您也可以使用Observable.bindCallback

// bindCallback is a factory factory, it creates a function that
// when called with any arguments will return an Observable that
// wraps setRemoteSdp, handling the callback portion for you.
// I'm using setRemoteSdp.bind(WebRTC) because I don't know
// if setRemoteSdp requires its calling context to be WebRTC
// so it's "just in case". It might not be needed.
const setRemoteSdpObservable = Observable.bindCallback(WebRTC.setRemoteSdp.bind(WebRTC));

setRemoteSdpObservable(peerConnection, sdp)
  .subscribe(d => console.log(d));

史诗中的用法就是这样的

// observables are lazy, so defining this outside of our epic
// is totally cool--it only sets up the factory
const setRemoteSdpObservable = Observable.bindCallback(WebRTC.setRemoteSdp.bind(WebRTC));

function receivedSdp(action$, store) {
  return action$.ofType(VideoStream.RECEIVED_SDP)
    .mergeMap(action => {
      const {peerConnection} = store.getState().videoStreams;
      const {sdp} = action.payload;

      return setRemoteSdpObservable(peerConnection)
        .map(result => myReducer.myAction());
    })
};

您可以使用它为所有WebRTC apis创建Observable包装。