如何使用 RxJS Observables 制作倒数计时器? [英] How to make countdown timer with RxJS Observables?
问题描述
我正在努力使用 Observables 创建倒数计时器,示例在 http://reactivex.io/documentation/operators/timer.html 似乎不起作用.在这个特定示例中,与 timerInterval 相关的错误不是从计时器返回的 Observable 的函数.
我也一直在尝试其他方法,我想出的最好的方法是:
Observable.interval(1000).take(10).subscribe(x => console.log(x));
这里的问题是它从 0 计数到 10,我想要一个倒数计时器,例如10,9,8...0.
我也试过这个,但是 timer
对于 Observable 类型不存在
Observable.range(10, 0).timer(1000).subscribe(x => console.log(x));
以及,根本不产生任何输出.
Observable.range(10, 0).debounceTime(1000).subscribe(x => console.log(x));
<块引用>
澄清我需要关于 ReactiveX 的 RxJS 实现的帮助,而不是 MircoSoft 版本.
你在正确的轨道上 - 你的问题是 timer
在原型上不存在(因此在 Observable.range()
) 但在 Observable 上(参见 RxJS 文档).IE.jsbin
const start = 10;Rx.Observable.timer(100, 100)//timer(firstValueDelay, intervalBetweenValues).map(i => start - i).take(开始 + 1).subscribe(i => console.log(i));//或者Rx.Observable.range(0, 开始 + 1).map(i => start - i).subscribe(i => console.log(i));
I'm struggling to create a countdown timer using Observables, the examples at http://reactivex.io/documentation/operators/timer.html do not seem to work. In this specific example the error related to timerInterval not being a function of the Observable returned from timer.
I have also been experimenting with other approaches and the best I've come up with is:
Observable.interval(1000).take(10).subscribe(x => console.log(x));
The problem here is it counts up from 0 to 10 and I want a countdown timer e.g. 10,9,8...0.
I've also tried this but the timer
does not exist for type Observable
Observable.range(10, 0).timer(1000).subscribe(x => console.log(x));
As well as, which produces no output at all.
Observable.range(10, 0).debounceTime(1000).subscribe(x => console.log(x));
To clarify I need help with ReactiveX's RxJS implementation, not the MircoSoft version.
You were on the right track - your problem was that timer
does not exist on the prototype (and thereby on Observable.range()
)but on Observable (see the RxJS docs). I.e. jsbin
const start = 10;
Rx.Observable
.timer(100, 100) // timer(firstValueDelay, intervalBetweenValues)
.map(i => start - i)
.take(start + 1)
.subscribe(i => console.log(i));
// or
Rx.Observable
.range(0, start + 1)
.map(i => start - i)
.subscribe(i => console.log(i));
这篇关于如何使用 RxJS Observables 制作倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!