1 of 10

Custom Operators in RxJS

Quinn James

2 of 10

RxJS Operators in General

  • RxJS does functional programming to streams of “observable” data.
    • Streams: mouse clicks, API responses
  • An observable is like an async array.
  • To return a filtered copy array of only odd numbers in plain JS:
    • ar.filter(x => x % 2 === 1)

3 of 10

RxJS Operators in General

  • [Image from reactivex.io documentation]

  • The syntax is identical:
    • ar.filter(x => x % 2 === 1)

4 of 10

Custom Operators

  • In functional programming, composing functions together is supposed to be easy.
  • RxJS is a library, not a language. So, there are a few limitations.
  • Many of these have to do with tree shaking.
  • Used to be harder in Rx4 (letProto etc)

5 of 10

Approach #1: Wildcard

  • Import all the things
  • This is easy to manage
  • But Rx is large

6 of 10

Approach #2: Patch

  • Import methods that patch Observable.prototype.
  • This saves the size of your webpack
  • But it’s a pain to manage, and worse if you’re writing a library

7 of 10

Pipeable Operators

  • Introduced to solve this problem
  • Makes tree shaking easy
  • The syntax is useful even for non-named chains

8 of 10

Approach #3 (Pipeable)

  • Just feed everything into a pipe to make a custom operator
  • You can feed your new operator into the pipe too

9 of 10

Full Custom Functions

  • A bit more
  • involved.
  • You have to
  • handle
  • errors and
  • resubscribe

[code is from RxJS

Github docs]

10 of 10

Enjoy yourself!

  • Further reading:
    • Antonio Calapez
      • “RxJS 5.5, piping all the things"
    • Nicholas Jamieson
      • “RxJS: Understanding Lettable Operators”
    • Credit to rxjs docs for the marbles
    • Code is mine except where noted