Angular Signals & Observables: Differences

2023/07/15
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

Angular Signals, introduced in Angular 16, are a new reactivity primitive that developers are comparing to Observables. This article highlights the key differences between the two.

One important distinction is that Signals always have a value, while Observables can emit their values synchronously or asynchronously. Signals require the consumer to "pull" their value when needed, whereas Observables can push their values to subscribers.

To differentiate between Signals and Observables in code, the convention is to prefix Signal variables with a $ and suffix Observable variables with a $.

Another difference lies in the behavior of the combineLatest() function. With Observables, this function will not emit anything until every given observable emits at least one value. Signals, on the other hand, have no such limitation and will not cause any concerns.

Additionally, if one of the observables passed to combineLatest() completes before emitting a value, the resulting observable will instantly complete and not emit anything. Signals, however, do not have a "complete" state and will continue to emit an error until a non-error value can be produced.

Modifying one of the observables observed by combineLatest() can create an infinite loop in the resulting observable. In computed() and effect() functions, writing to signals is forbidden by default to prevent such loops.

Another distinction is that Signals do not emit their values directly. Instead, they notify the consumer, who decides when to pull the value. This behavior makes Signals "glitch-free" and can eliminate unnecessary execution cycles. However, in cases where immediate execution is required, an observable with withLatestFrom() can be used.

Overall, understanding the differences between Angular Signals and Observables is crucial for developers working with Angular 16 and beyond.