![](/img/trans.png)
[英]Rxjs: Observable with takeUntil(timer) keeps emitting after the timer has ticked
[英]how to take an action after takeUntil rxjs function
因此,如果 function 运行时间足够长以触发在计时器上运行的 takeUntil function,我试图让 boolean 为真。
这是代码
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;
return 0;
}
),
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)
)),
takeUntil(endtimer)
).subscribe();
}
本质上,如果 takeUntil 确实被解雇,我希望将 boolean 设置为 true。
timeout = true;
我一直在看这个stackoverflow帖子
但事情并没有我想要的那么清楚。
当条件( endtimer
)触发时,您可以使用合并运算符并重用您的takeUntil
条件来创建映射的true
值:
const { Subject, merge } = rxjs; const { takeUntil, mapTo } = rxjs.operators; const source$ = new Subject(); const condition$ = new Subject(); // Use the merge to work around your completed observable const result$ = merge( // When your condition fires map this event to true condition$.pipe(mapTo(true)), // Your already existing pipe in wich the takeUntil lives source$.pipe( takeUntil(condition$) ) ) result$.subscribe(console.log) source$.next(1); source$.next(2); condition$.next(); source$.next(3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
仅供参考:我不确定此解决方案是否适用于您的应用程序上下文,因为您没有显示声明和设置timeout
的位置。
takeUntil
完成 observable,因此要在完成后执行操作,您可以在几个地方执行此操作:
completion
处理程序中:this.start.pipe(
switchMap(() => timer(0, 5000).pipe(
tap(() => console.log('Polling every 5s')),
mergeMap(() => this.poll))
),
takeUntil(endtimer)
)
.subscribe(
next => console.log('handling next value'),
error => console.log('handling error'),
() => this.timeout = true // <--- this fires after observable completes
);
finalize
运算符:this.start.pipe(
switchMap(() => timer(0, 5000).pipe(
tap(() => console.log('Polling every 5s')),
mergeMap(() => this.poll))
),
takeUntil(endtimer),
finalize(() => this.timeout = true)
)
.subscribe();
注意:这些解决方案并不完全符合您的要求。 确实,当takeUntil
触发时它们会触发,但它们也会因为 stream 完成的任何其他原因触发。 我认为这种区别在您的情况下并不重要,但想在整个问题的背景下提及。
正如 Sang Dang 在评论中提到的那样,您也可以从“计时器关闭时”的角度(而不是我迄今为止提到的“可观察对象完成时”)的角度来处理它,您可以通过简单地添加一个tap
您的计时器。
const endtimer = timer(60000).pipe(
tap(() => this.timeout = true)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.