Sub topic 3
Combining Streams, Sharing State, and Testing
This chapter assumes you can write pipe chains, use HttpClient, and subscribe safely with the async pipe or takeUntilDestroyed.
Combining Streams
Each combination operator decides when to emit in a different way.
| Operator | Emits when | Typical use |
|---|---|---|
| `combineLatest` | Any source emits, once every source has emitted at least once | Filters plus page number |
| `forkJoin` | Every source completes, and then only once | Parallel HTTP requests |
| `withLatestFrom` | Only the main source emits | Reading form state when a button is clicked |
import { BehaviorSubject, combineLatest, forkJoin, of } from 'rxjs';
forkJoin([of({ name: 'Ada' }), of([101, 102])])
.subscribe(([user, orders]) => console.log(user.name, orders.length));
const filter$ = new BehaviorSubject('all');
const page$ = new BehaviorSubject(1);
combineLatest([filter$, page$]).subscribe(([f, p]) => console.log(f, p));
page$.next(2); // logs "all 2"A common mistake is passing a source that never completes, such as valueChanges, to forkJoin. When that happens, forkJoin never emits.
Subjects
A subject is both an observable and an observer. You push values into it with next().
| Type | What a late subscriber receives |
|---|---|
| `Subject` | Only values sent after it subscribes |
| `BehaviorSubject` | The current value, then new values (requires an initial value) |
| `ReplaySubject(n)` | The last `n` values, then new values |
Cold vs Hot and shareReplay
An observable is cold when each subscriber starts its own producer. HttpClient is cold, so three async pipes on one request send three requests. An observable is hot when all subscribers share one producer. shareReplay({ bufferSize: 1, refCount: true }) makes a cold source hot: subscribers share one execution, and late subscribers get the cached value.
A BehaviorSubject State Service
Keep the subject private and expose only read-only observables. That way only the service's own methods can change the state.
import { Injectable } from '@angular/core';
import { BehaviorSubject, map } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly itemsSubject = new BehaviorSubject<string[]>([]);
readonly items$ = this.itemsSubject.asObservable();
readonly count$ = this.items$.pipe(map(items => items.length));
add(item: string): void {
this.itemsSubject.next([...this.itemsSubject.value, item]);
}
}Signals Interop
toSignal(this.cart.count$, { initialValue: 0 }) subscribes to the observable and exposes its latest value as a signal. It unsubscribes automatically when the component is destroyed. It must be called in an injection context, such as a field initializer or the constructor. toObservable(signal) converts in the other direction, which lets you use operators like debounceTime on a signal.
Marble Testing
TestScheduler runs streams on virtual time, so tests need no real timers. In a marble string, - is one frame, a letter is a value, and | marks completion.
import { TestScheduler } from 'rxjs/testing';
import { map } from 'rxjs';
it('doubles each value', () => {
const scheduler = new TestScheduler((a, e) => expect(a).toEqual(e));
scheduler.run(({ cold, expectObservable }) => {
const result$ = cold('-a-b-|', { a: 1, b: 2 }).pipe(map(x => x * 2));
expectObservable(result$).toBe('-a-b-|', { a: 2, b: 4 });
});
});Exercise
A dashboard loads a user and that user's settings from two HTTP calls and should render once both arrive. Which operator fits, and why not combineLatest?
Show answer
forkJoin fits, because it emits once after both HTTP observables complete. combineLatest would also work here, since each HTTP call emits once, but forkJoin states the intent "wait for all to finish" directly and never re-emits.
Exercise
Why does CartService expose items$ via asObservable() instead of making itemsSubject public?
Show answer
A public subject would let any component call next() and change the state. asObservable() hides next(), so all changes go through the service's methods.