Do you know the burden of handling your RxJs subscriptions manually? Did you ever forget one? Wouldn’t it be nice if we never have to think about subscriptions again? Let’s explore the options in this article.

Do you know the burden of handling your RxJs subscriptions manually? Did you ever forget one? Did you ever run into the problem that you thought you would be safe with the use of the async pipe in the template and then after some time a new requirement comes in and you realise that you need a subscribe call in your component class as well? This may be a smell for a bad design of some of your components, but let’s be honest: Sometimes it is the right way in order to get things done.

Wouldn’t it be nice if we never have to think about subscriptions again?

No more manual handling of subscription arrays.

No more takeUntil(this.destroyed$)

No more subscription.add()

No more pain and fear ;)

We can achieve that with the help of Typescript Transformers at build time.

What are typescript transformer?

Typescript Transformers allow us to hook into the compilation process of Typescript and transform the Abstract Syntax Tree (AST) that is produced.

This allows us to change the existing code at compile time. In the following sections of this post we will, for example, use it to:

  • find all classes with a @Component() decorator
  • find all calls to subscribe() of RxJs
  • generate methods like ngOnDestroy
  • extend the body of existing methods

This is a very powerful process and it is heavily used by the  Angular compilation process itself.

To get a feeling for an AST it helps to take a look at an example at  astexplorer.net. On the left side of this explorer you can see the source of the component class TestComponent and on the right side its AST representation. You can change the code on the left and the AST is immediately updates. This tool will become incredibly helpful later when we want to find out how to write the transformer code to extend the existing source or generate new parts.

#typescript #angular

Having fun with Angular and Typescript Transformers - Angular
1.80 GEEK