RxJS: Avoiding Unbound Methods

Photo by pan xiaozhen on Unsplash

I often see code that looks a little like this:

Which seems fine.

Well, it is fine — as long as the and methods do not depend upon the context in their implementations.

Why might this be a bad thing?

When unbound methods are passed to RxJS, they will be invoked with an unexpected context for . If the method implementations don’t use , they will behave as you would expect.

However, there are a number of reasons why, as a general rule, you might want to avoid passing unbound methods:

  • If you are in the habit of passing unbound methods, it’s a near certainty that you will, eventually, introduce a bug by passing, as unbound, a method that uses in its implementation. Maybe you’ll have a test that picks it up; maybe you won’t.
  • Passing unbound methods is something that’s often done with error handlers. And the unit testing of code paths for errors is often neglected.
  • The callbacks passed to — and some operators — are invoked with a instance as the context. That can make debugging any context-related issues more complicated, as will not be ; it will be a valid object instance — just not the instance you were expecting.
  • If a method’s implementation is changed to use , anywhere it’s passed as unbound will have to be changed, too. Again, this is something that often happens with error handling: an initial implementation that writes to the console might be changed to instead report the error to a service — accessed via the context.

What are the alternatives?

If the method does not use , it can instead be written as a static method or as a stand-alone function — rather than a method.

If the method does use , it can be passed via an arrow function:

Or can be called to explicitly bind :

At the moment, if is called, the type information is lost, but with the merging of this PR from Anders Hejlsberg, a future release of TypeScript will, eventually, have a strongly-typed .

Using a TSLint rule

TSLint is a fantastic tool for enforcing these sorts of statically-analysable rules. I’ve added an rule to — a suite of TSLint rules that can be used to ensure an RxJS codebase is clean and hygienic.

So if passing unbound methods is something you’d like to avoid, too, install the package and switch on the rule.

TSLint includes a built-in rule which is related, but is a little different. That rule exists to prevent methods that don’t use from being written in the first place — which might or might not be what you want.

This post is also published on my personal blog: ncjamieson.com.

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store