javascript / expert
Snippet
Reactive Stream Conversion with toSignal
The `toSignal` utility bridges the gap between RxJS Observables and Angular Signals. It subscribes to the observable and updates a signal whenever a new value is emitted. This allows developers to use powerful RxJS operators for data processing while maintaining the simplicity and performance benefits of Signals for UI rendering.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { toSignal } from '@angular/core/rxjs-interop';import { interval } from 'rxjs';@Component({ ... })export class DashboardComponent {private timer$ = interval(1000);// Converting Observable to Signal for synchronous template accessreadonly tick = toSignal(this.timer$, { initialValue: 0 });constructor() {effect(() => console.log('Current tick:', this.tick()));}}
angular
Breakdown
1
readonly tick = toSignal(this.timer$, { initialValue: 0 });
Converts the stream into a read-only signal that provides the latest value synchronously.
2
effect(() => console.log(...));
Signals used inside effects are automatically tracked, even when they originated from an Observable.