Published on

Signals vs Observables in Angular

Authors
  • avatar
    Name
    John Dockery
    Twitter

Choosing Between Signals and Observables

Angular 16 introduces signals, a new and interesting way to handle asynchronous operations compared to traditional observables. Understanding when to use signals versus observables can help you write cleaner and more maintainable code. In this post, I want to discuss what I have seen to be the strengths of each and provide examples to illustrate their use.

When to Use Signals

Signals are ideal for straightforward asynchronous scenarios where simplicity and readability are paramount. They offer a more declarative API compared to observables, making them easier to understand and maintain. Signals are particularly useful for handling events or asynchronous operations that don't require complex manipulation or chaining of operators.

For instance, signals can be used to handle button clicks or user inputs in a form:

import { Signal } from 'angular';

const buttonClickSignal = new Signal();

buttonClickSignal.subscribe(() => {
  console.log('Button clicked!');
});

Here, a signal is created to handle button clicks, and a subscription is set up to log a message when the button is clicked.

When to Use Observables

Observables are better suited for complex asynchronous scenarios where you need to manipulate and combine multiple data streams. They provide a wide range of operators and utilities for transforming, filtering, and combining data streams, making them ideal for scenarios such as making HTTP requests or handling real-time data updates.

For example, observables probably should be used to fetch data from an API and process the response:

import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

const apiUrl = 'https://api.example.com/data';

const dataObservable = new Observable<any>((observer) => {
  this.http.get(apiUrl).subscribe((response) => {
    observer.next(response);
    observer.complete();
  });
});

dataObservable.subscribe((data) => {
  console.log('Data received:', data);
});

In this example, an observable is created to fetch data from an API using Angular's HttpClient module. A subscription is set up to log the received data.

Making the Choice

Choosing between signals and observables depends on the complexity of your asynchronous operations. If you need to handle simple events or operations with minimal complexity, signals are a good choice. For more complex scenarios involving multiple data streams and transformations, observables offer more flexibility and power.

By understanding the strengths of each approach, you can choose the right tool for the job and write cleaner, more maintainable code in your Angular projects.