takeLast vs take

RxJS Pipeable operators vs. Dot-chaining

đź“Ł UPDATE: this article now takes the form of an RxJS Explorer:

Visit reactive.how/rxjs/explorer

Animation from Episode 27 - JavaScript Pipeline Operator.

RxJS <5.5 and dot-chaining

Prior to RxJS 5.5, you were dot-chaining the operators like this:

const stream = Observable.interval(TICK)
  .take(LENGTH)
  .map(gaussian)

RxJS 5.5.* and pipeable operators

RxJS 5.5 introduced pipeable operators and pipe:

// Pull in only what you need:
import { take, map } from 'rxjs/operators';
import { interval } from 'rxjs/observable/interval';

const stream = interval(TICK).pipe(
  take(LENGTH),
  map(gaussian)
)

Read why this is is a better approach:
github.com/ReactiveX/rxjs/…/pipeable-operators.md#why

You can now easily build your own operators and chain them with the RxJS ones:

// Create your own operator based on RxJS map:
const draw = brush =>
  map(num =>
    brush.repeat(Math.floor(num * 65))
  )

const stream = interval(TICK).pipe(
  take(LENGTH),
  map(gaussian),
  draw("•")
)

RxJS 6 beta and rx-compat

RxJS 6 is coming soon. If you have a code base with dot-chaining operators, you can still use it thanks to the compatibility package rx-compat. It adds operators to Observable.prototype and creation methods to Observable.

The future

JavaScript |> pipeline operator

There is a pipeline operator proposal. In particular, it allows you to write your code like this:

const draw = brush =>
  map(num =>
    num * 65 |> Math.floor |> brush.repeat
  )

const stream =
  interval(TICK)
  |> take(LENGTH)
  |> map(gaussian)
  |> draw("•")

Read my babel+prettier+ligature configuration in Episode 27 - Pipeline Operator to try the pipeline operator yourself.

A new episode every Monday


Episode 22 - scan vs. reduce

đź“® You can subscribe to the mailing list to receive new episodes right inside your inbox. Or follow me on Twitter.

CĂ©dric Soulas Follow Hire me

Freelance Developer Advocate. Motion graphics with code. JavaScript and Elm. cedricsoulas.com

Subscribe to reactive.how newsletter

Join the Newsletter

Learn Reactive Programming and stay up-to-date:

Receive my latest news, product updates and programming visualizations. You can unsubscribe at any time.

Highlights

@CedricSoulas

Making an illustrated book!

The Illustrated Book of RxJS

Learn more →