Custom RxJS 5 operators

While still in beta, I think RxJS 5 is absolutely awesome! One of the most underrated features of RxJS 4 is (or was?) the ability to define custom operators using let. While let is still supported in RxJS 5, it’s more elegant to define custom operators using regular functions and apply them using the proposed :: operator.

You can read more about the this-binding syntax in the ES7 proposal. Essentially it defines a nicer syntax for applying an unbound function to an arbitrary object.

Let’s say we want to define a custom operator that increments numbers by a fixed constant:

ArrayObservable.create([1, 2, 3])
  ::map(x => x + 5)
  .subscribe(x => console.log(x)) // #=> 6, 7, 8

We might want to extract out ::map(x => x + 5) into a reusable factory that creates an observable that can be applied to the ArrayObservable:

function increment (plus) {
  return this::map(x => x + plus)
}

ArrayObservable.create([1, 2, 3])
  ::increment(5)
  .subscribe(x => console.log(x))

And that’s how easy it is to define custom operators in RxJS 5!

Alternatively we can use an arrow function and apply it using letProto (just like in RxJS 4):

const increment = plus => observable =>
  observable::map(x => x + plus)

ArrayObservable.create([1, 2, 3])
  ::letProto(increment(5))
  .subscribe(x => console.log(x))

Further reading:

 
7
Kudos
 
7
Kudos

Now read this

How I hacked the Bower Registry and what I learned from it

Bower is a front-end package manager created at Twitter. It has about 20k active users and solves a real problem: Front-end package management. Two weeks ago, I stumbled upon a huge security risk allowing me to manipulate the underlying... Continue →