Sawtaytoes
12/14/2018 - 1:43 PM

RxJS Iterator Subject Implementation

createIteratorSubject allows someone to create an observable out of a generator and tell RxJS when to pull the next value instead of relying on the official implementation which creates backpressure.

const { BehaviorSubject, Subject } = require('rxjs')
const { map, tap, withLatestFrom } = require('rxjs/operators')

const createIteratorSubject = (
  iterator,
) => {
  const iterator$ = (
    new BehaviorSubject()
  )

  const pushNextValue = ({
    done,
    value,
  }) => {
    done
    && value === undefined
    ? (
      iterator$
      .complete()
    )
    : (
      iterator$
      .next(value)
    )
  }

  iterator$
  .push = (
    value,
  ) => (
    pushNextValue(
      iterator
      .next(value)
    )
  )

  iterator$
  .push()

  return iterator$
}

module.exports = createIteratorSubject