[英]How to cancel inner observable timer using rxjs?
I am trying to make a simple counter with Observable timer. 我试图用Observable计时器做一个简单的计数器。 Outside time runs every 5 seconds.
外部时间每5秒运行一次。 And inner timer runs every one second because I would like to output something like the following:
内部计时器每秒钟运行一次,因为我想输出以下内容:
Loading.. 5 正在加载.. 5
Loading.. 4 载入中.. 4
Loading.. 3 正在加载.. 3
... ...
But my problem is the inner observable does not cancel. 但是我的问题是内在可观察性并没有消除。 It continues infinitely.
它无限地继续。 What is the correct way of doing this?
正确的做法是什么?
Observable.timer(0, 5000)
.pipe(
tap(() => {
Observable.timer(0, 1000)
.subscribe(t => console.log(5 - t));
}),
tap(t => {
this.count = this.users.length;
}),
).subscribe();
Use switchMap operator to cancel outer observable 使用switchMap运算符取消外部可观察
Observable.timer(0, 5000)
.pipe(
switchMap(() => {
return Observable.timer(0, 1000);
}),
tap(t => {
console.log(`%c`, 'background:red', 5 - (t));
this.count = this.users.length;
}),
).subscribe();
I think what you are looking for is the take
operator, see [ http://reactivex.io/documentation/operators/take.html](the docs) for further explanation. 我认为您正在寻找的是
take
运算符,请参阅[ http://reactivex.io/documentation/operators/take.html](文档)以获取更多说明。 You can use take(5)
or take(6)
, depending if you want to count down to 0 or 1. 您可以使用
take(5)
或take(6)
,具体取决于您要倒数到0还是1。
Observable.timer(0, 5000)
.pipe(
tap(() => {
Observable.timer(0, 1000)
.take(5)
.subscribe(t => console.log(5 - t));
}),
tap(t => {
this.count = this.users.length;
}),
).subscribe();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.