switchMap - countdown

RxJS 5 switchMap

by Brian Troncone

HTML

<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
<h4>
Time remaining: <span id="remaining"></span>
</h4>
<button id="pause">
Pause Timer
</button>
<button id="resume">
Resume Timer
</button>

JavaScript

const countdownSeconds = 60;
const setHTML = id => val => document.getElementById(id).innerHTML = val;
const pauseButton = document.getElementById('pause');
const resumeButton = document.getElementById('resume');
const interval$ = Rx.Observable.interval(1000).mapTo(-1);

const pause$ = Rx.Observable.fromEvent(pauseButton, 'click').mapTo(Rx.Observable.of(false))
const resume$ = Rx.Observable.fromEvent(resumeButton, 'click').mapTo(interval$);

const timer$ = Rx.Observable
	.merge(pause$, resume$)
  .startWith(interval$)
  .switchMap(val => val)
  .scan((acc, curr) => curr ? curr + acc : acc, countdownSeconds)
  .subscribe(setHTML('remaining'));