Sub topic 7
Turning a signal into an observable with toObservable
This chapter assumes you can create and read signals with signal() and computed(). It also assumes you know basic RxJS (subscribe, map, switchMap) and what an injection context is. The previous chapters covered toSignal. Here you go the other way: you take a signal and make it a stream that RxJS operators can work on.
Why convert a signal to an observable
A signal holds one current value and has no notion of time. RxJS has operators built around time: debounceTime, switchMap, throttleTime, retry, bufferTime. A signal has no equivalent for them.
Suppose a query signal changes on every keystroke. You want to wait 300 ms after the last keystroke, cancel any in-flight request, and then fetch. That is stream logic. toObservable turns the signal into a stream so you can use those operators.
The function lives in @angular/core/rxjs-interop:
function toObservable<T>(
source: Signal<T>,
options?: { injector?: Injector },
): Observable<T>;It takes any Signal<T>, including a computed() or a read-only signal, and returns an Observable<T>. It never errors on its own, and it completes when the injector it was created in is destroyed.
A first example
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
@Component({
selector: 'app-greeting',
template: `
<input (input)="name.set($any($event.target).value)" />
<p>{{ name() }}</p>
`,
})
export class Greeting {
name = signal('world');
constructor() {
toObservable(this.name)
.pipe(map((n) => n.trim().toUpperCase()))
.subscribe((n) => console.log('Name is now', n));
}
}The component constructor is an injection context, so the call is legal. The subscriber logs once with the initial value (WORLD) and again after each change. You never unsubscribe by hand here, for reasons covered below.
How it works internally
The mechanism explains most of the behavior you will see. Conceptually, toObservable does this:
- It creates a
ReplaySubjectwith a buffer size of 1. - It creates an
effect()in the current injector. The effect reads the signal and pushes the value into the subject. - It registers a destroy callback on the injector that stops the effect and completes the subject.
- It returns the subject as an observable.
This has four consequences.
- The effect is created when you call
toObservable, not when someone subscribes. The signal is tracked from that point on, even if nobody listens. - Emissions are asynchronous. The effect does not run at the moment you call
set(). It runs the next time Angular flushes effects, which is normally part of change detection. - Late subscribers get the latest value. The buffer holds one value, so a subscriber that arrives after the first emission receives the most recent value immediately.
- Signal equality filters the stream. An effect re-runs only when the signal's value changes. Setting a signal to a value it already holds (by
Object.is, or by a customequalfunction) produces no emission.
The initial value
Because the buffer is filled by the effect, the first emission is the signal's value at the time the effect first runs. That is not necessarily the value at the time you called toObservable.
Compare this with toSignal, where you had to think about the first value. With toObservable there is always a value, because every signal always has one. The only question is when it is delivered.
Here is the case from the plan, with two set calls before the effect has a chance to run:
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-demo',
template: ``,
})
export class Demo {
n = signal(0);
constructor() {
toObservable(this.n).subscribe((v) => console.log(v));
this.n.set(1);
this.n.set(2);
// The effect has not run yet. When it does, it reads 2.
// The subscriber logs 2 once. It never sees 0 or 1.
}
}This skipping of intermediate values is useful for performance, and it can also surprise you. The next chapter covers it in detail. For now, remember that toObservable gives you the settled value of a signal at each effect flush, and it is not a log of every set call.
The injection context requirement
toObservable creates an effect, and effects need an injector. Without one, it throws at runtime with an error about effect() or toObservable being called outside an injection context.
These places work without any extra setup:
- a constructor
- a field initializer
- a function passed to
runInInjectionContext - a factory for a provider or
inject-based function
A regular method called later does not. To use it there, pass an injector:
import { Injectable, Injector, Signal, inject } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class Watcher {
private injector = inject(Injector);
watch<T>(source: Signal<T>): Observable<T> {
// Called from a normal method, so an injector must be supplied.
return toObservable(source, { injector: this.injector });
}
}The injector's lifetime sets the observable's lifetime. A root service's injector lives as long as the application, so every call to watch creates an effect that lives that long. If you call watch repeatedly, you leak effects. For short-lived work, pass the injector of a component or another scoped object, so the stream completes when that object is destroyed.
Cleanup and completion
You get cleanup on one side only. The effect and the subject are tied to the injector, so when the component is destroyed:
- the effect stops tracking the signal
- the subject completes
- subscribers receive a
completenotification
This means that in a component, a subscription made to a toObservable stream is cleaned up when the component is destroyed. Subscribers also stop receiving values in that case, because the source has completed. You do not need takeUntilDestroyed for the source itself.
You still need to think about other things you merge in. If you combine the stream with a long-lived observable, such as a service-level subject, the combined stream completes only when all sources complete (for combineLatest) or never completes. A pipeline built from toObservable plus a root-level stream can outlive the component. For that case, add takeUntilDestroyed() explicitly.
import { Component, signal } from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { interval, combineLatest } from 'rxjs';
@Component({
selector: 'app-mixed',
template: ``,
})
export class Mixed {
threshold = signal(10);
constructor() {
combineLatest([toObservable(this.threshold), interval(1000)])
.pipe(takeUntilDestroyed())
.subscribe(([limit, tick]) => {
if (tick > limit) console.log('Over the limit');
});
}
}Using computed signals as sources
Any signal works as a source. Passing a computed() is often cleaner than combining several streams afterward:
import { Component, computed, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { distinctUntilChanged } from 'rxjs';
@Component({
selector: 'app-paging',
template: ``,
})
export class Paging {
page = signal(1);
pageSize = signal(20);
// One derived value that changes when either input changes.
offset = computed(() => (this.page() - 1) * this.pageSize());
offset$ = toObservable(this.offset).pipe(distinctUntilChanged());
}The computed already suppresses emissions when the result is unchanged, because a computed signal notifies dependents only when its value changes. The distinctUntilChanged here is redundant for primitives, and it is shown only to point out that signal equality has already done that work. For object values with a custom equal function, the filtering follows that function. A distinctUntilChanged operator would use === unless you give it a comparator.
Reading the signal inside the pipeline
A common mistake is to read other signals inside RxJS operators and expect the stream to react:
toObservable(this.query).pipe(
switchMap((q) => this.http.get('/api', { params: { q, page: this.page() } })),
);The this.page() call runs inside switchMap, outside any reactive context, so the pipeline does not re-run when page changes. It reads whatever page holds at that moment. If page should trigger a new request, put it into the stream. Either combine two toObservable calls, or derive one computed that contains both values and convert that:
import { computed, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { switchMap } from 'rxjs';
const query = signal('');
const page = signal(1);
const params = computed(() => ({ q: query(), page: page() }));
// params$ emits whenever either signal changes.
const params$ = toObservable(params);Note that params creates a new object each time, so the default equality (Object.is) treats every recomputation as a change. That is the right behavior here, because the computation runs only when query or page changed.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `toObservable` in a click handler or other method | Throws an injection context error | Pass `{ injector }` or call it in a field initializer |
| Expecting a synchronous emission after `subscribe` | The subscriber receives nothing until effects flush | Treat emissions as asynchronous, and read the signal directly if you need the value now |
| Expecting every `set` to emit | Intermediate values are skipped | Use a `Subject` for events |
| Calling `toObservable` repeatedly with a long-lived injector | Effects accumulate until the injector is destroyed | Create the stream once, or use a short-lived injector |
| Reading a second signal inside `switchMap` | The stream does not react to that signal | Include it in the source stream |
Summary of behavior
toObservable(signal)returns an observable backed by aReplaySubject(1)that an effect feeds.- The signal is tracked from the moment you call it. Subscribing is not required.
- Emissions are asynchronous and coalesced. Only the value at the time of the effect flush is delivered.
- Unchanged values do not emit, following the signal's equality rule.
- It needs an injection context, or an explicit
injectoroption. - It completes when the injector is destroyed.
Exercise
A component has count = signal(0). In its constructor it runs toObservable(this.count).subscribe(v => console.log(v)); and then this.count.set(5); this.count.set(5); this.count.set(7);, all in the same synchronous block. What does the subscriber log, and why? Then, in a separate method called from a button click, a developer writes toObservable(this.count) with no options. What goes wrong, and what are two ways to fix it?
Show answer
The subscriber logs 7 once. The effect inside toObservable has not run when the three set calls happen. When it runs, it reads the current value, 7, and pushes it into the ReplaySubject. The earlier values 0 and 5 are never delivered, and the second set(5) would not have emitted anyway because the value was unchanged. In the click handler, toObservable is called outside an injection context, so creating its internal effect throws an error. Fix it by passing an injector, as in toObservable(this.count, { injector: this.injector }) with injector = inject(Injector) stored as a field, or by moving the call to a field initializer or constructor and reusing the resulting observable in the method.