您的位置:首页 > Web前端 > JavaScript

[RxJS] Toggle A Stream On And Off With RxJS

2016-03-15 21:15 483 查看
This lesson covers how to toggle an observable on and off from another observable by showing how to use a checkbox as a toggle for a stream of data.

<!DOCTYPE html>
<html>
<head>
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-alpha.8/dist/global/Rx.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="checkbox" id="toggle">
<div id="display"></div>
</body>
</html>


const display = document.querySelector('#display');
const toggle = document.querySelector('#toggle');

const source$ = Rx.Observable.interval(100)
.map(() => '.');
const checked$ = Rx.Observable.fromEvent(toggle, 'change')
.map(e => e.target.checked);
const sourceThatStop$ = source$.takeUntil(checked$);

checked$
.filter( flag => flag === true)
.switchMapTo( sourceThatStop$ )
.subscribe( (x) => {
display.innerHTML += x;
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: