问题描述
所以下面的代码是根据我在 this 堆栈溢出问题中得到的答案开发的。
该代码旨在轮询我的服务器,直到服务器上的条件为真,或者轮询已发生一分钟。
我知道我可以使用 takeuntil
RXJS 函数在一分钟后停止轮询。然而,我不知道我会把它放在代码中的哪个位置。就像我把它放在我认为它会去的每个地方一样,代码出错了。
我也在使用来自 learnrxjs 网站 https://www.learnrxjs.io/learn-rxjs/operators/filtering/takeuntil
的本教程您会注意到 startastream()
函数的第一行是
const endtimer = timer(60000);
这是填充 takeuntil()
参数的条件。所以takeuntil(endtimer)
start$ = this.http.get(environment.shochat_content_creator_set_valid_stream_start).pipe(
tap(() => console.log('Stream start'))
);
poll$ = this.http.get(environment.check_if_stream_is_active_on_mux).pipe(
tap(() => (this.streamready = true)),catchError(error => {
console.log(error);
return EMPTY;
})
);
startastream(){
const endtimer = timer(60000);
this.streampollsubscription = this.start$.pipe(
switchMap(() => timer(0,5000).pipe(
tap(() => console.log('Polling every 5s')),mergeMap(() => this.poll$)
))
).subscribe();
}
解决方法
你可以简单地把它放在 switchMap 之后的管道中:
this.streampollsubscription = this.start$.pipe(
switchMap(() => timer(0,5000).pipe(
tap(() => console.log('Polling every 5s')),mergeMap(() => this.poll$)
)),takeUntil(endtimer)
).subscribe();
看看这个StackBlitz。