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

Introducing The NERD Stack

Don’t be MEAN! Be a friendly NERD! During my 2 day Hackathon project and the subsequent short project phase at Hack Reactor, I needed an easy to use stack suited for agile development. Typically, people choose the popular MEAN Stack for... Continue →