RXJS倒数计时器突然停止,我发现当没有发出可信赖的数据时,它会被switchMap取消。
如何解决?我需要通过单击按钮启动计时器。 请找到我的例子的jsbin
const start = Rx.Observable.fromEvent(document.querySelector('#btn'), 'click');
start
.switchMap(() => {
return Rx.Observable.timer(0, 1000)
.takeUntil(Rx.Observable.timer(60000 + 1000))
})
.map((value) => 60000 - value * 1000)
.map(function(i) {
return 'Timer (second): ' + i / 1000;
}).subscribe(function(text) {
var container = document.querySelector('#app');
container.textContent = text;
});

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>RxJS 5 Operators</title>
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.3/dist/global/Rx.umd.js"></script>
</head>
<body>
<button id='btn'> start </button>
<p id='app'></p>
</body>
</html>
&#13;
答案 0 :(得分:1)
尝试将takeUntil(...)
更改为take(...)
发件人:强>
.takeUntil(Rx.Observable.timer(60000 + 1000))
以强>
.take(60000 / 1000 + 1)
猜测原因:
如果计时器累积了时间错误,takeUntil
可能会在预期的计时器事件发生之前被触发。
time
[0] 0.000
[1] 1.103
...
[59] 60.234
61.003 <- takeUntil fired
[60] 61.123 <- expected last event lost
答案 1 :(得分:0)
const start$ = Rx.Observable.fromEvent(document.querySelector('#btn'), 'click');
start$
.switchMap(()=> {
return Rx.Observable.timer(0, 1000)
.takeUntil(Rx.Observable.timer(3000 + 1000))
.map(value => 3000 - value * 1000)
.map(function (i) {
return 'Timer (second): ' + i/1000;
});
})
.subscribe(function (text) {
var container = document.querySelector('#app');
container.textContent = text;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>RxJS 5 Operators</title>
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.3/dist/global/Rx.umd.js"></script>
</head>
<body>
<button id='btn'> start </button>
<p id='app'></p>
</body>
</html>