Skip to content
Brian Cavalier edited this page Nov 4, 2017 · 3 revisions

Retry a stream up to N times after failures.

import { throwError, recoverWith } from 'most'

// retry :: number -> Stream a -> Stream a
// return a stream that retries the behavior of the input
// stream up to n times after errors. n must be >= 0.
// When n === 0, the returned stream will be indistinguishable
// from the input stream.
const retry = (n, stream) =>
  recoverWith(e => n <= 0 ? throwError(e) : retry(n - 1, stream),
    stream)

Retry a stream up to N times with a delay between retries.

import { throwError, recoverWith, switchLatest, delay, just } from 'most'

// retry :: number -> number -> Stream a -> Stream a
// Given a stream, return a new stream that retries
// the original after an ms delay.  Each subsequent failure
// will back off by doubling the previous ms
const retry = (n, ms, s) =>
  recoverWith(e => n === 0
    ? throwError(e)
    : backoff(n - 1, ms, s), s)

// Just delaying s won't work: we have to produce a delayed
// stream *containing s*, and then flatten that with
// switchLatest() or join()
const backoff = (n, ms, s) =>
  switchLatest(delay(ms, just(retry(n, ms, s))))