Learn RxJS
  • Introduction
  • Learn RxJS
    • Operators
      • Combination
        • combineAll
        • combineLatest
        • concat
        • concatAll
        • endWith
        • forkJoin
        • merge
        • mergeAll
        • pairwise
        • race
        • startWith
        • withLatestFrom
        • zip
      • Conditional
        • defaultIfEmpty
        • every
        • iif
        • sequenceEqual
      • Creation
        • ajax
        • create
        • defer
        • empty
        • from
        • fromEvent
        • generate
        • interval
        • of
        • range
        • throw
        • timer
      • Error Handling
        • catch / catchError
        • retry
        • retryWhen
      • Multicasting
        • publish
        • multicast
        • share
        • shareReplay
      • Filtering
        • audit
        • auditTime
        • debounce
        • debounceTime
        • distinct
        • distinctUntilChanged
        • distinctUntilKeyChanged
        • filter
        • find
        • first
        • ignoreElements
        • last
        • sample
        • single
        • skip
        • skipUntil
        • skipWhile
        • take
        • takeLast
        • takeUntil
        • takeWhile
        • throttle
        • throttleTime
      • Transformation
        • buffer
        • bufferCount
        • bufferTime
        • bufferToggle
        • bufferWhen
        • concatMap
        • concatMapTo
        • exhaustMap
        • expand
        • groupBy
        • map
        • mapTo
        • mergeMap / flatMap
        • mergeScan
        • partition
        • pluck
        • reduce
        • scan
        • switchMap
        • switchMapTo
        • toArray
        • window
        • windowCount
        • windowTime
        • windowToggle
        • windowWhen
      • Utility
        • tap / do
        • delay
        • delayWhen
        • dematerialize
        • finalize / finally
        • let
        • repeat
        • timeInterval
        • timeout
        • timeoutWith
        • toPromise
      • Full Listing
    • Subjects
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
    • Recipes
      • Alphabet Invasion Game
      • Battleship Game
      • Breakout Game
      • Car Racing Game
      • Catch The Dot Game
      • Click Ninja Game
      • Flappy Bird Game
      • Game Loop
      • Horizontal Scroll Indicator
      • Http Polling
      • Lockscreen
      • Matrix Digital Rain
      • Memory Game
      • Mine Sweeper Game
      • Platform Jumper Game
      • Progress Bar
      • Save Indicator
      • Smart Counter
      • Space Invaders Game
      • Stop Watch
      • Swipe To Refresh
      • Tank Battle Game
      • Tetris Game
      • Type Ahead
      • Uncover Image Game
    • Concepts
      • RxJS Primer
      • Get started transforming streams with map, pluck, and mapTo
      • Time based operators comparison
      • RxJS v5 -> v6 Upgrade
Powered by GitBook
On this page
  • Example Code
  • Operators Used
  1. Learn RxJS
  2. Recipes

Stop Watch

PreviousSpace Invaders GameNextSwipe To Refresh

Last updated 1 year ago

By

This recipe demonstrates RxJS implementation of Stop Watch, inspired by talk by

Example Code

( )

Stop Watch

index.ts

// RxJS v6+
import { fromEvent, interval, merge, noop, NEVER } from 'rxjs';
import { map, mapTo, scan, startWith, switchMap, tap } from 'rxjs/operators';

interface State {
  count: boolean;
  countup: boolean;
  speed: number;
  value: number;
  increase: number;
}

const getElem = (id: string): HTMLElement => document.getElementById(id);
const getVal = (id: string): number => parseInt(getElem(id)['value']);
const fromClick = (id: string) => fromEvent(getElem(id), 'click');
const fromClickAndMapTo = (id: string, obj: {}) =>
  fromClick(id).pipe(mapTo(obj));
const fromClickAndMap = (id: string, fn: _ => {}) =>
  fromClick(id).pipe(map(fn));
const setValue = (val: number) =>
  (getElem('counter').innerText = val.toString());

const events$ = merge(
  fromClickAndMapTo('start', { count: true }),
  fromClickAndMapTo('pause', { count: false }),
  fromClickAndMapTo('reset', { value: 0 }),
  fromClickAndMapTo('countup', { countup: true }),
  fromClickAndMapTo('countdown', { countup: false }),
  fromClickAndMap('setto', _ => ({ value: getVal('value') })),
  fromClickAndMap('setspeed', _ => ({ speed: getVal('speed') })),
  fromClickAndMap('setincrease', _ => ({ increase: getVal('increase') }))
);

const stopWatch$ = events$.pipe(
  startWith({
    count: false,
    speed: 1000,
    value: 0,
    countup: true,
    increase: 1
  }),
  scan((state: State, curr): State => ({ ...state, ...curr }), {}),
  tap((state: State) => setValue(state.value)),
  switchMap((state: State) =>
    state.count
      ? interval(state.speed).pipe(
          tap(
            _ =>
              (state.value += state.countup ? state.increase : -state.increase)
          ),
          tap(_ => setValue(state.value))
        )
      : NEVER
  )
);

stopWatch$.subscribe();

index.html

<style>
  input,
  #counter,
  #controls {
    text-align: center;
    margin: auto;
  }

  #counter {
    font-size: 50px;
  }

  #controls {
    width: 50%;
  }
</style>

<div id="counter">0</div>
<div id="controls">
  <fieldset>
    <legend>Setup</legend>
    <button id="start">start</button>
    <button id="pause">pause</button>
    <button id="reset">reset</button>
  </fieldset>
  <fieldset>
    <legend>Count</legend>
    <button id="countup">count up</button>
    <button id="countdown">count down</button>
  </fieldset>
  <fieldset>
    <legend>Set to</legend>
    <input id="value" value="0"></input>
    <br/>
    <button id="setto">set value</button>
  </fieldset>
  <fieldset>
    <legend>Speed</legend>
    <input id="speed" value="1000"></input>
    <br/>
    <button id="setspeed">set speed</button>
  </fieldset>
  <fieldset>
    <legend>Increase</legend>
    <input id="increase" value="1"></input>
    <br/>
    <button id="setincrease">set increase</button>
  </fieldset>
</div>

Operators Used

  • NEVER

  • noop

fromEvent
interval
map
mapTo
merge
scan
startWith
switchMap
tap
adamlubek
RxJS Advanced Patterns – Operate Heavily Dynamic UI’s
@Michael_Hladky
StackBlitz