我正在研究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;
})
答案 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;
})