Angular Computed Signal with an Observable
Tags: angular, signals, rxjs, webdev
Published: 2024-02-18 22:36:58

Angular signals provide a robust reactivity system, streamlining the data flow within Angular applications and also improving the developer experience.
However, their integration with RxJS can sometimes present challenges, leading to messy and less straightforward code.

In this blog post, we'll explore a strategy to streamline the interaction between Angular signals and RxJS, making their combined usage more straightforward and efficient.

## Scenario - Pokédex
In an attempt to show some of the problems I created this simple scenario where we have a simple Pokémon display, and we use an API to get the Pokémon information. We can click on the Previous and the Next to iterate over the Pokédex, and the Refresh should re-fetch the information from the API.

![print from the app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qy8a66x0lj44p7tue9ex.png)


There are only two components, the `AppComponent` that contains the buttons, and the `PokemonComponent` that displays the information and makes the API calls.

The `PokemonComponent` has an `id` signal input and if it changes the component makes a new API call to get the Pokémon info. There is also the `refresh()` that must re-call the API for the current `id`.

```ts
@Component({
  selector: 'app-root',
  template: `
    <button (click)="id=id-1">Previous</button>
    <button (click)="pokemonComp.refresh()">Refresh</button>
    <button (click)="id=id+1">Next</button>
    <app-pokemon #pokemonComp [id]="id"/>
  `
})
export class AppComponent {
  id = 1;
}

@Component({
  selector: 'app-pokemon',
  template: `
    <h1>{{ pokemon()?.name }}</h1>
    <img [src]="pokemon()?.sprites?.front_default">
  `,
})
export class PokemonComponent {
  http = inject(HttpClient);

  id = input.required<number>();

  id$ = toObservable(this.id);
  refresh$ = new BehaviorSubject(null);
  pokemon$ = combineLatest([this.id$, this.refresh$]).pipe(
    switchMap(([id]) => this.http.get(`https://pokeapi.co/api/v2/pokemon/${id}`)),
  );

  pokemon = toSignal(this.pokemon$);

  refresh() {
    this.refresh$.next(null);
  }
}
```

## How to improve - computedAsync

The code above works but there is a lot of code gymnastic needed to make sure the Signal world and the RxJs world work together, from the `toObservable`, `toSignal`, and the `combileLatest`, and `refresh$` it all feels a bit too clunky.

If we forget the observables and focus on what we are trying to do, we want a kind of `computed` that could unwrap the observable and store its value in the signal.

```ts
// Receives a function that must return an observable
function computedAsync<T>(computation: () => Observable<T>): Signal<T> {

  // Creates a signal that where the observable result will be stored
  const sig = signal<T>(null);

  // Uses effect to make sure that if there are changes in the computation
  // that it gets re-runned
  effect(() => {
    // Reset signal value
    sig.set(null);
    // Get the observable
    const observable = computation();
    // Subscribe and store the result in the signal
    observable.subscribe((result) => sig.set(result));
  }, { allowSignalWrites: true });

  return sig;
}
```

With this, we already gain the amazing power of working the RxJs while depending on signals, this will simplify the code a lot as we will see soon.
But there are a few problems that we still need to solve, first, we need to find a way to replicate the refresh functionality, and second, we need to make sure to not leave open observable subscriptions.

```ts
function computedAsync<T>(computation: () => Observable<T>): Signal<T> & { recompute: () => void } {

  const sig = signal<T>(null);

  // Save current subscription to be able to unsubscribe 
  let subscription: Subscription;

  // Create an arrow function that contains the signal updating logic
  const recompute = () => {
    sig.set(null);
    // Before making the new subscription, unsub from the previous one
    if (subscription && !subscription.closed) {
      subscription.unsubscribe();
    }
	const observable = computation();
    subscription = observable.subscribe((result) => sig.set(result));
  };

  effect(recompute, { allowSignalWrites: true });

  // Add the recompute function to the returned signal, so that it can be called from the outside
  return Object.assign(sig, { recompute });
}
```

## Let's put it to use

Let's see how our `PokemonComponent` looks if we use the `computedAsync`.

```ts
@Component({
  selector: 'app-pokemon',
  template: `
    <h1>{{ pokemon()?.name }}</h1>
    <img [src]="pokemon()?.sprites?.front_default">
  `,
})
export class PokemonComponent {
  http = inject(HttpClient);

  id = input.required<number>();

  pokemon = computedAsync(() => this.http.get(`https://pokeapi.co/api/v2/pokemon/${this.id()}`));

  refresh() {
    this.pokemon.recompute();
  }
}
```

I don't know about you but this feels like a huge improvement to the original code, there are no gymnastics to make sure the observables are triggered at the right time and no boilerplate `toObservable` and `toSignal`. 

I think that the signals API is one of the best things that Angular added, it is very powerful and flexible, and with the deeper integration in the framework with will for sure get better. Let me know our thoughts about this in the comments. 🙂