如何在takeWhile中使用rxjs缓冲区

时间:2020-06-21 13:07:24

标签: rxjs buffer

我正在研究webrtc。该应用程序将icecandidates发送到后端Firestore服务器。 问题在于,多次触发onicecandidate导致多次调用信令服务器。我想收集所有的候选人,并打一个电话到信令服务器。 这个想法是缓冲所有事件,直到iceGathering完成。下面的这种尝试不起作用

this.pc = new RTCPeerConnection(iceServers);
const source: Observable<any> =  fromEvent(this.pc, 'icecandidate');
const takeWhile$ = source
        .pipe(
            takeWhile(val=> val.currentTarget.iceGatheringState === 'gathering'
    ))
const buff = source.pipe(buffer(takeWhile$));
    buff.subscribe(() => {
        // this.pc.onicecandidate = onicecandidateCallback;
    })

1 个答案:

答案 0 :(得分:0)

方法1:

你快到了。

takeWhile$接受值并在满足条件时发出它们。因此,在buff中,每当takeWhile$发出一个值时,buff就会发出一个icecandidate个事件的缓冲区。

因此,您只需要在takeWhile$中发出一个值即可。

因此,您需要的是takeLast()运算符,只发出最后一个值。

takeLast(1)放在takeWhile$中时,它仅发出最后一个值,而在buff中,最后发出的值导致创建icecandidate事件的缓冲区。

this.pc = new RTCPeerConnection(iceServers);

const source: Observable<any> = fromEvent(this.pc, "icecandidate");

const takeWhile$ = source.pipe(
  takeWhile(val => val.currentTarget.iceGatheringState === "gathering"),
  takeLast(1)
);

const buff = source.pipe(buffer(takeWhile$));

buff.subscribe((bufferValues) => {

   // bufferValues has a buffer of icecandidate events

  // this.pc.onicecandidate = onicecandidateCallback;
});

您可以使用以上代码中的icecandidate来访问预订中的bufferValues个事件的缓冲区。

方法2:

您还可以使用reduce运算符来实现相同的情况

this.pc = new RTCPeerConnection(iceServers);

const source: Observable<any> = fromEvent(this.pc, "icecandidate");

const takeWhile$ = source.pipe(
  takeWhile(val => val.currentTarget.iceGatheringState === "gathering"),
  reduce((acc, val) => [...acc,val], [])
);

takeWhile$.subscribe((bufferValues) => {

  // bufferValues has a buffer of icecandidate events

 // this.pc.onicecandidate = onicecandidateCallback;
})
相关问题