[RxJS] Toggle A Stream On And Off With RxJS

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;
});

 

posted @ 2016-03-15 21:15  Zhentiw  阅读(281)  评论(0编辑  收藏  举报