ExamplesAdvanced counters

Configurable interval

import {useMemo, useState} from 'react'
import {useObservable} from 'react-rx'
import {timer} from 'rxjs'
import {map, startWith} from 'rxjs/operators'

export default function App() {
  const [delay, setDelay] = useState(500)
  const observable = useMemo(
    () =>
      timer(500, delay).pipe(
        map((n) => `Count: ${n}`),
        startWith('Starting counter…'),
      ),
    [delay],
  )

  const label = useObservable(observable)
  return (
    <>
      Counter interval (ms):{' '}
      <input
        type="range"
        min={0}
        max={1000}
        step={100}
        value={delay}
        onChange={(e) =>
          setDelay(Number(e.currentTarget.value))
        }
      />
      {delay}
      <div>{label}</div>
    </>
  )
}

Open on CodeSandboxOpen Sandbox

Delayed tick

import {useObservable} from 'react-rx'
import {timer} from 'rxjs'

import {Ticker} from './Ticker'
import {TickerWithSubTick} from './TickerWithSubTick'

const observable = timer(0, 1000)

export default function App() {
  const tick = useObservable(observable, 0)

  return (
    <>
      <div>Tick: {tick}</div>
      <Ticker observable={observable} />
      <TickerWithSubTick
        observable={observable}
      />
    </>
  )
}

Open on CodeSandboxOpen Sandbox

Fizz Buzz

import {useObservable} from 'react-rx'
import {timer} from 'rxjs'
import {map, take} from 'rxjs/operators'

const observable = timer(0, 500).pipe(
  map((n) => n + 1),
  map((n) => {
    const divBy3 = n % 3 === 0
    const divBy5 = n % 5 === 0
    const divBy3And5 = divBy3 && divBy5
    return divBy3And5
      ? 'Fizz Buzz'
      : divBy3
        ? 'Fizz'
        : divBy5
          ? 'Buzz'
          : String(n)
  }),
  map((n, i) => (
    <h1>
      {i + 1}: {n}
    </h1>
  )),
  take(100),
)

export default function App() {
  return useObservable(observable)
}

Open on CodeSandboxOpen Sandbox