Testing the Boundary Between Angular Signals and RxJS

If a typing delay comes before the switch to a new query, the old search can finish during that delay. Its results appear beneath text that now asks for something else.
Both requests can be perfectly valid. The problem is when the old one stopped being relevant.
For this catalogue search, RxJS owns the sequence of inputs and requests. Angular reads the latest search state through one toSignal conversion. The interesting part is making that division hold when a request fails, someone presses Retry, or the component disappears halfway through a delay.
The example uses Angular 22.2.6, RxJS 7.8.2, and TypeScript 6.0.3. The local implementation and test commands include a working component, simulated requests, and tests using Angular and RxJS. The catalogue contains tools such as hammers and clamps. The example doesn't call a real HTTP service. You can download the catalogue search example and tests.
One Owner for the Result
The screen needs to distinguish an empty query, a typing delay, an active read, a result, and a failure. Keeping the query alongside each state also lets the template explain which search failed.
export type Product = Readonly<{ id: string; name: string }>;
export type SearchCommand = Readonly<{ query: string; retry?: boolean }>;
export type SearchState =
| Readonly<{ status: 'idle'; query: '' }>
| Readonly<{ status: 'waiting' | 'loading'; query: string }>
| Readonly<{ status: 'success'; query: string; items: readonly Product[] }>
| Readonly<{ status: 'error'; query: string; message: string }>;An empty successful result is still success, with an empty array. It doesn't need to become an error. This version clears the previous results as soon as the query changes, rather than leaving results for "hammer" beneath an input containing "clamp". Keeping stale results visible is a reasonable alternative, but it needs an explicit stale state and labelling.
I've covered Signals and derived values and state carried through RxJS separately. Here, the result has one owner: the stream. Copying it into another writable signal would give the component a second place to update loading, errors, and results.
The signal is the view's current value. It isn't an event log. If several stream values arrive synchronously, don't depend on the template displaying every intermediate value. Anything that must process every notification belongs in the stream or its consumer, with cleanup for when it's no longer needed.
Cancel Before Starting the Next Delay
The ordering of the operators changes what "cancel the old search" means. A pipeline shaped like debounceTime(300), switchMap(readCatalogue) won't reach switchMap for the new query until the delay has elapsed. The previous read remains subscribed during that interval.
This implementation switches immediately, then waits inside the newly selected branch:
commands.pipe(
map(command => ({ ...command, query: command.query.trim() })),
distinctUntilChanged((previous, current) =>
!current.retry && previous.query === current.query),
switchMap(({ query, retry: explicitRetry }) => {
if (!query) return of(initialState);
return concat(
of<SearchState>({ status: 'waiting', query }),
timer(explicitRetry ? 0 : 300, scheduler).pipe(
switchMap(() => concat(
of<SearchState>({ status: 'loading', query }),
defer(() => readCatalogue(query)).pipe(
// Retry, map to success, and catch errors here.
),
)),
),
);
}),
);This is the outer portion of createSearch; the request operators follow below. Its injected scheduler is asyncScheduler in normal use and a real RxJS TestScheduler in the timing tests.
A changed query unsubscribes the previous branch immediately, whether that branch is waiting, reading, or waiting to retry. Clearing the input also cancels work immediately and returns to idle. Trimming and comparison avoid repeating the same ordinary search. Retry is an explicit command because a person should be able to repeat an unchanged query after a failure.
The Retry button skips the 300 ms typing delay. Its zero‑delay timer still schedules the work; it doesn't make the request synchronous.
Unsubscribing protects the current subscriber from later notifications. What happens to the underlying work depends on the reader's teardown. The tests include a deliberately uncooperative producer that finishes after teardown: its output cannot replace the current view. That doesn't prove a remote server stopped processing anything.
Keep a Failure Inside Its Request
The injected reader returns an Observable of validated product arrays. The example defines CatalogueReadError, an Error subclass with a numeric status. A real HTTP adapter would translate appropriate responses into that type, validate incoming data, and provide suitable messages. It shouldn't display arbitrary server diagnostics to the person searching.
These are the operators inside the request's pipe:
retry({
count: 1,
delay: cause => cause instanceof CatalogueReadError && cause.status === 503
? timer(100, scheduler)
: throwError(() => cause),
}),
map((items): SearchState => ({ status: 'success', query, items })),
catchError((cause: unknown) => of<SearchState>({
status: 'error', query,
message: cause instanceof Error ? cause.message : 'Could not load the catalogue.',
})),This policy allows one automatic retry of a catalogue read after a classified 503 failure. Other failures become error state immediately. I've kept the wait short at 100 ms for this example. In a real application, choose the delay from the service's retry guidance, rate limits, and how long you expect the outage to last.
defer calls the reader when subscribed and calls it again for the retry. It also brings a synchronous exception from the reader factory into the Observable's error path. Returning a fresh read matters when retrying: reusing an already‑started Promise would simply observe the same operation again.
The catchError belongs inside the switched request. If recovery sits outside the entire command pipeline and replaces it with a single error value, that replacement can complete the stream. The error message appears correctly, then the next query does nothing. A reassuringly tidy screen can still contain a dead search box.
This retry policy applies to reads. Repeating a write requires a separate decision about duplicate effects and idempotency; changing the method's name from readCatalogue to submitOrder would not settle that question.
Convert Once, Within the Component's Lifetime
The component creates its conversion in a field initialiser, where Angular supplies an injection context:
private readonly commands = new Subject<SearchCommand>();
readonly state = toSignal(createSearch(
this.commands, inject(CATALOGUE_READER), inject(SEARCH_SCHEDULER),
), { initialValue: initialState });Angular's RxJS interop documentation explains that toSignal subscribes immediately and normally cleans up when its creating component or service is destroyed. Reuse the returned signal. Each successful call subscribes again, so keep the conversion out of frequently called getters.
initialValue gives the template a defined idle state before any input arrives. requireSync would be the wrong promise for this command stream: a plain Subject doesn't emit a current search state when subscribed. A dedicated test confirms that Angular rejects a source that fails that synchronous‑emission requirement.
Errors need deliberate treatment too. An unhandled Observable error is thrown when the resulting signal is read. Converting failures into the typed state above lets the template render a recoverable error instead. Another test checks the raw throwing behaviour so that the distinction isn't hidden by the helper.
The template keeps an initially empty role="status" node in place. It receives completed result counts or the current failure message. Waiting and loading remain ordinary visible text, avoiding a non‑empty status update for every stage of typing. Retry returns focus to the persistent search input before its button disappears. The tests check those changes in the DOM. You'll still need to listen to the updates with the screen readers you support.
Test the Timings and the Actual View
Using a virtual clock lets us check exactly when cancellation happens. In one test, the first read starts at 300 ms. A new query arrives at 310 ms, and the old subscription ends at 310 ms. The replacement read starts at 610 ms. An assertion only about the final result would miss that 300 ms difference.
The retry test has similarly explicit frames: subscribe at 300 ms, fail at 310 ms, resubscribe at 410 ms, fail finally at 420 ms. Those timings come from the test clock; they aren't measurements of a network request.
The suite has 18 passing tests: ten exercise the RxJS pipeline, five mount the real Angular component, and three check toSignal directly. Component tests destroy the view during the typing delay, an active read, and a retry wait. Each checks that the relevant subscription or scheduled work is disposed, with no subsequent read beginning.
The mounted tests use Angular's zoneless scheduler and wait for whenStable(). They don't call detectChanges() after every interaction to make the expected text appear. That would conceal a missing change notification, a distinction covered in Angular's zoneless testing guidance. A separate Chrome run bootstraps the same component and checks success, failure, Retry, stale output, and destruction.
These checks extend the usual Angular component testing approach into the gaps between interactions. Most of the interesting failures happen after the first result has already worked.
Keep the Boundary Local until Sharing is Necessary
This search belongs to one component. Its destruction should end the search. Moving the conversion into a root‑provided service would give it a different lifetime, which may be appropriate for a shared feature but should be intentional.
A wider NgRx or SignalStore decision needs requirements this example doesn't have, such as shared ownership across screens. Likewise, optimising derived signal values addresses a different part of the rendering work.
For this screen, we can test the important behaviour directly: a new query cancels the old branch immediately, a failed read leaves the next command usable, and leaving the screen ends its subscription. Once those rules hold, the choice between reading an Observable and reading a signal is a much less exciting part of the implementation. That's a good outcome for a search box.