We use cookies to enhance your experience on the site
CodeWorlds

Signals vs RxJS

When to use Signals?

Signals are better for:

  • Simple component state
  • Synchronous values
  • Simple derived calculations
  • UI state (loading, error, data)

When to use RxJS?

RxJS is better for:

  • Asynchronous streams (HTTP, WebSocket)
  • Complex data transformations
  • Debounce, throttle, retry
  • Handling multiple data sources

Integration of Signals with RxJS

1import { toSignal, toObservable } from '@angular/core/rxjs-interop';
2import { interval } from 'rxjs';
3
4@Component({...})
5export class HybridComponent {
6  // Observable → Signal
7  private timer$ = interval(1000);
8  timerSignal = toSignal(this.timer$, { initialValue: 0 });
9
10  // Signal → Observable
11  count = signal(0);
12  count$ = toObservable(this.count);
13
14  constructor() {
15    // Usage in an effect
16    effect(() => {
17      console.log('Timer:', this.timerSignal());
18    });
19  }
20}

linkedSignal (Angular 19)

1import { signal, linkedSignal } from '@angular/core';
2
3const sourceSignal = signal('original');
4
5// linkedSignal resets when source changes
6const derived = linkedSignal(() => sourceSignal() + ' - modified');
7
8sourceSignal.set('new');
9// derived automatically = 'new - modified'

resource() API (Angular 19)

1import { resource } from '@angular/core';
2
3@Component({...})
4export class SamuraiDetailComponent {
5  id = input.required<number>();
6
7  // Automatic data fetching
8  samuraiResource = resource({
9    request: () => this.id(),
10    loader: async ({ request: id }) => {
11      const response = await fetch(\`/api/samurai/\${id}\`);
12      return response.json();
13    }
14  });
15
16  // Accessing data
17  // this.samuraiResource.value()   - data
18  // this.samuraiResource.status()  - 'loading' | 'success' | 'error'
19  // this.samuraiResource.error()   - error
20}
Go to CodeWorlds