From 41ed7a9b83787d668246b1b6976633523621e968 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:07:24 -0500 Subject: [PATCH 1/4] Add failing specs for retrying transient errors and lesson 06 --- ...retry-transient-errors.interceptor.spec.ts | 107 ++++++++++++++++++ .../lessons/lesson-06-rxjs.spec.ts | 57 ++++++++++ .../lessons/search-race.spec.ts | 40 +++++++ 3 files changed, 204 insertions(+) create mode 100644 src/app/shared/retry-transient-errors.interceptor.spec.ts create mode 100644 src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts create mode 100644 src/app/thoughts-content/lessons/search-race.spec.ts diff --git a/src/app/shared/retry-transient-errors.interceptor.spec.ts b/src/app/shared/retry-transient-errors.interceptor.spec.ts new file mode 100644 index 0000000..2829917 --- /dev/null +++ b/src/app/shared/retry-transient-errors.interceptor.spec.ts @@ -0,0 +1,107 @@ +import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { appConfig } from '../app.config'; +import { retryTransientErrors } from './retry-transient-errors.interceptor'; + +const UNAVAILABLE = { status: 503, statusText: 'Service Unavailable' }; + +describe('retryTransientErrors', () => { + let http: HttpClient; + let backend: HttpTestingController; + let result: unknown; + let failure: { status?: number } | undefined; + + const get = (url = '/repos') => + http.get(url).subscribe({ next: (body) => (result = body), error: (error) => (failure = error) }); + + beforeEach(() => { + vi.useFakeTimers(); + result = undefined; + failure = undefined; + TestBed.configureTestingModule({ + providers: [provideHttpClient(withInterceptors([retryTransientErrors])), provideHttpClientTesting()], + }); + http = TestBed.inject(HttpClient); + backend = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + backend.verify(); + vi.useRealTimers(); + }); + + it('retries a GET that hit a 5xx, after a backoff delay', () => { + get(); + backend.expectOne('/repos').flush('down', UNAVAILABLE); + + backend.expectNone('/repos'); + vi.advanceTimersByTime(500); + backend.expectOne('/repos').flush(['angular-paul']); + + expect(result).toEqual(['angular-paul']); + expect(failure).toBeUndefined(); + }); + + it('treats a network failure (status 0) as transient too', () => { + get(); + backend.expectOne('/repos').error(new ProgressEvent('error')); + vi.advanceTimersByTime(500); + backend.expectOne('/repos').flush([]); + + expect(result).toEqual([]); + }); + + it('backs off longer each time, then gives up after two retries with the last error', () => { + get(); + backend.expectOne('/repos').flush('down', UNAVAILABLE); + vi.advanceTimersByTime(500); + backend.expectOne('/repos').flush('down', UNAVAILABLE); + + vi.advanceTimersByTime(500); + backend.expectNone('/repos'); + vi.advanceTimersByTime(500); + backend.expectOne('/repos').flush('still down', UNAVAILABLE); + + vi.advanceTimersByTime(10_000); + backend.expectNone('/repos'); + expect(failure?.status).toBe(503); + }); + + it('does not retry a client error like 404', () => { + get(); + backend.expectOne('/repos').flush('nope', { status: 404, statusText: 'Not Found' }); + + vi.advanceTimersByTime(10_000); + backend.expectNone('/repos'); + expect(failure?.status).toBe(404); + }); + + it('never retries a POST, which might not be safe to send twice', () => { + http.post('/messages', { text: 'hi' }).subscribe({ error: (error) => (failure = error) }); + backend.expectOne('/messages').flush('down', UNAVAILABLE); + + vi.advanceTimersByTime(10_000); + backend.expectNone('/messages'); + expect(failure?.status).toBe(503); + }); +}); + +describe('retryTransientErrors in the app config', () => { + it('is registered on the app HttpClient', () => { + TestBed.configureTestingModule({ providers: [...appConfig.providers, provideHttpClientTesting()] }); + vi.useFakeTimers(); + const backend = TestBed.inject(HttpTestingController); + let result: unknown; + + TestBed.inject(HttpClient) + .get('https://api.github.com/users/gpbsumido/repos') + .subscribe((body) => (result = body)); + backend.expectOne(() => true).flush('down', UNAVAILABLE); + vi.advanceTimersByTime(500); + backend.expectOne(() => true).flush([]); + + expect(result).toEqual([]); + vi.useRealTimers(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts b/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts new file mode 100644 index 0000000..2edd1c8 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts @@ -0,0 +1,57 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { LESSON_PAGES } from './lessons'; +import { Lesson06Rxjs } from './lesson-06-rxjs'; + +expect.extend(axeMatchers); + +describe('Lesson06Rxjs', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const text = (selector: string) => el.querySelector(selector)?.textContent ?? ''; + const type = async (value: string) => { + const input = el.querySelector('#race-query')!; + input.value = value; + input.dispatchEvent(new Event('input')); + await fixture.whenStable(); + }; + + beforeEach(async () => { + vi.useFakeTimers(); + await TestBed.configureTestingModule({ imports: [Lesson06Rxjs] }).compileComponents(); + fixture = TestBed.createComponent(Lesson06Rxjs); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + afterEach(() => vi.useRealTimers()); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-06-rxjs']).toBeDefined(); + }); + + it('teaches at three levels, then pitfalls and interview questions', () => { + const headings = [...el.querySelectorAll('h2')].map((h) => h.textContent?.trim()); + expect(headings).toEqual( + expect.arrayContaining(['Simple', 'Intermediate', 'Expert', 'Pitfalls', 'Interview questions']), + ); + }); + + it('typing fast leaves mergeMap showing a stale query and switchMap the current one', async () => { + await type('s'); + await type('si'); + await type('sig'); + await vi.advanceTimersByTimeAsync(2000); + await fixture.whenStable(); + + expect(text('#race-merge')).toContain('"s"'); + expect(text('#race-switch')).toContain('"sig"'); + }); + + it('has no axe violations', async () => { + vi.useRealTimers(); + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/search-race.spec.ts b/src/app/thoughts-content/lessons/search-race.spec.ts new file mode 100644 index 0000000..ec1add0 --- /dev/null +++ b/src/app/thoughts-content/lessons/search-race.spec.ts @@ -0,0 +1,40 @@ +import { delay, Observable, of } from 'rxjs'; +import { TestScheduler } from 'rxjs/testing'; +import { searchAsYouType } from './search-race'; + +/** + * Marble tests: virtual time, so a 100ms delay costs nothing and the order of + * arrivals is exact. Inside run(), every rxjs timer uses the test scheduler. + * + * The fake search answers a one-letter query slowly (100ms) and a longer one + * quickly (20ms), like a real backend where broad queries cost more. + */ +const search = (query: string): Observable => + of(`results for ${query}`).pipe(delay(query.length === 1 ? 100 : 20)); + +describe('searchAsYouType', () => { + let scheduler: TestScheduler; + + beforeEach(() => { + scheduler = new TestScheduler((actual, expected) => expect(actual).toEqual(expected)); + }); + + it('with mergeMap, the slow stale response lands last and wins', () => { + scheduler.run(({ hot, expectObservable }) => { + const typed = hot('a 9ms b', { a: 'a', b: 'ab' }); + expectObservable(typed.pipe(searchAsYouType('mergeMap', search))).toBe('30ms x 69ms y', { + x: 'results for ab', + y: 'results for a', + }); + }); + }); + + it('with switchMap, a new query cancels the one in flight', () => { + scheduler.run(({ hot, expectObservable }) => { + const typed = hot('a 9ms b', { a: 'a', b: 'ab' }); + expectObservable(typed.pipe(searchAsYouType('switchMap', search))).toBe('30ms x', { + x: 'results for ab', + }); + }); + }); +}); From 84e2bc21dedaaf7c4782a6ecc16b63800bd2abe2 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:08:08 -0500 Subject: [PATCH 2/4] Retry transient GET failures with backoff --- src/app/app.config.ts | 8 +++-- .../retry-transient-errors.interceptor.ts | 36 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/app/shared/retry-transient-errors.interceptor.ts diff --git a/src/app/app.config.ts b/src/app/app.config.ts index 963c9f5..5352390 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -14,10 +14,11 @@ import { provideBrowserGlobalErrorListeners, provideZonelessChangeDetection, } from '@angular/core'; -import { provideHttpClient, withFetch } from '@angular/common/http'; +import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; +import { retryTransientErrors } from './shared/retry-transient-errors.interceptor'; import { provideClientHydration, withEventReplay, @@ -32,7 +33,10 @@ export const appConfig: ApplicationConfig = { // Covered properly in lesson 09. provideZonelessChangeDetection(), // HttpClient backed by fetch() instead of XHR — required for good SSR. - provideHttpClient(withFetch()), + // [ng-06 rxjs] Interceptors run in array order on the way out and reverse + // order on the way back. withInterceptors() takes plain functions; the + // class-based HTTP_INTERCEPTORS multi-provider is the legacy form. + provideHttpClient(withFetch(), withInterceptors([retryTransientErrors])), provideRouter(routes), // SSR hydration: reuse server-rendered DOM instead of re-creating it. // Lesson 12. diff --git a/src/app/shared/retry-transient-errors.interceptor.ts b/src/app/shared/retry-transient-errors.interceptor.ts new file mode 100644 index 0000000..ee23e14 --- /dev/null +++ b/src/app/shared/retry-transient-errors.interceptor.ts @@ -0,0 +1,36 @@ +import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http'; +import { retry, throwError, timer } from 'rxjs'; + +const MAX_RETRIES = 2; +const BASE_DELAY_MS = 400; + +// [ng-06 rxjs] A functional interceptor: a plain function that sees every +// request HttpClient makes. `next(req)` sends it on and returns the response +// as an Observable, so the interceptor can pipe operators onto it. +// +// Simple: one blip on the network used to show the Projects app's error +// state. Now GETs get two more tries before anyone sees an error. +// Intermediate: retry() resubscribes to the source on error. HttpClient +// Observables are cold, so resubscribing *sends the request again*. That's +// what makes this work, and why it must stay away from POSTs. +// Expert: retry's `delay` returns an Observable. When it emits, retry tries +// again; when it errors, the error goes downstream. So "don't retry a 404" +// is just throwError() from the delay function, and the backoff is a +// timer() that doubles: 400ms, then 800ms. +export const retryTransientErrors: HttpInterceptorFn = (req, next) => { + // Only GETs are safe to send twice. A retried POST could submit twice. + if (req.method !== 'GET') return next(req); + + return next(req).pipe( + retry({ + count: MAX_RETRIES, + delay: (error, retryCount) => + isTransient(error) ? timer(BASE_DELAY_MS * 2 ** (retryCount - 1)) : throwError(() => error), + }), + ); +}; + +/** Status 0 is a network failure (offline, DNS, CORS); 5xx is the server's problem. */ +function isTransient(error: unknown): boolean { + return error instanceof HttpErrorResponse && (error.status === 0 || error.status >= 500); +} From 48edf3ca5593062d4d57fe77c09877623aa7f691 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:11:10 -0500 Subject: [PATCH 3/4] Write lesson 06 with a switchMap vs mergeMap race --- .../lessons/lesson-06-rxjs.spec.ts | 8 +- .../lessons/lesson-06-rxjs.ts | 325 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 1 + .../thoughts-content/lessons/search-race.ts | 20 ++ src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 6 files changed, 362 insertions(+), 4 deletions(-) create mode 100644 src/app/thoughts-content/lessons/lesson-06-rxjs.ts create mode 100644 src/app/thoughts-content/lessons/search-race.ts diff --git a/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts b/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts index 2edd1c8..022d72e 100644 --- a/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts +++ b/src/app/thoughts-content/lessons/lesson-06-rxjs.spec.ts @@ -11,15 +11,16 @@ describe('Lesson06Rxjs', () => { let el: HTMLElement; const text = (selector: string) => el.querySelector(selector)?.textContent ?? ''; + // Under fake timers the zoneless scheduler's own timeouts are fake too, so + // advancing the clock is what runs change detection, not whenStable(). const type = async (value: string) => { const input = el.querySelector('#race-query')!; input.value = value; input.dispatchEvent(new Event('input')); - await fixture.whenStable(); + await vi.advanceTimersByTimeAsync(20); }; beforeEach(async () => { - vi.useFakeTimers(); await TestBed.configureTestingModule({ imports: [Lesson06Rxjs] }).compileComponents(); fixture = TestBed.createComponent(Lesson06Rxjs); await fixture.whenStable(); @@ -40,18 +41,17 @@ describe('Lesson06Rxjs', () => { }); it('typing fast leaves mergeMap showing a stale query and switchMap the current one', async () => { + vi.useFakeTimers(); await type('s'); await type('si'); await type('sig'); await vi.advanceTimersByTimeAsync(2000); - await fixture.whenStable(); expect(text('#race-merge')).toContain('"s"'); expect(text('#race-switch')).toContain('"sig"'); }); it('has no axe violations', async () => { - vi.useRealTimers(); expect(await axe(el)).toHaveNoViolations(); }); }); diff --git a/src/app/thoughts-content/lessons/lesson-06-rxjs.ts b/src/app/thoughts-content/lessons/lesson-06-rxjs.ts new file mode 100644 index 0000000..16cfaf9 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-06-rxjs.ts @@ -0,0 +1,325 @@ +import { Component, signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { delay, filter, Observable, of } from 'rxjs'; +import { THOUGHTS } from '../thoughts-data'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; +import { searchAsYouType, SearchStrategy } from './search-race'; + +interface SearchResult { + query: string; + titles: string[]; +} + +/** + * A pretend server: searches the real thought titles, but a one-letter query + * takes 1.2s and a three-letter one 0.25s. Broad queries being slower is + * realistic, and it's what makes the race visible when typing at normal speed. + */ +function slowSearch(query: string): Observable { + const latencyMs = query.length === 1 ? 1200 : query.length === 2 ? 700 : 250; + const titles = THOUGHTS.map((t) => t.title).filter((title) => + title.toLowerCase().includes(query.toLowerCase()), + ); + return of({ query, titles }).pipe(delay(latencyMs)); +} + +@Component({ + selector: 'app-lesson-06-rxjs', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + template: ` + +

Simple

+

+ A signal is a value now. An Observable is values over time: keystrokes, + HTTP responses, websocket messages, timers. You subscribe() to get them, and + an Observable does nothing until someone does. +

+

+ HttpClient returns Observables. They're cold: each subscribe sends a + new request, and one that never gets subscribed never sends anything. In a component, + don't subscribe by hand. Turn the stream into a signal with toSignal() (or + the async pipe in older code), and Angular unsubscribes for you when the + component is destroyed. +

+ + +

Intermediate

+

+ Operators are functions you pipe() a stream through: + map, filter, debounceTime, + distinctUntilChanged, catchError. The ones that matter most in + interviews are the four that map each value to another Observable. They differ only + in what happens to the inner stream still running when the next value arrives: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Higher-order mapping operators +
OperatorWhen a new value arrives mid-flightUse it for
switchMapcancels the old inner streamsearch, route params: only the latest matters
mergeMapruns both, in parallelindependent work, like deleting several items
concatMapqueues the new one until the old finisheswrites that must stay in order
exhaustMapignores the new valuea submit button pressed twice
+ + +
+ + +
+

+ Type "sig" at normal speed. One letter takes 1.2s to answer, three letters 0.25s, so the + answers come back in reverse order. +

+
+
+ mergeMap + @if (mergeResult(); as result) { + showing "{{ result.query }}": {{ result.titles.length }} matches + } @else { + waiting for a search + } +
+
+ switchMap + @if (switchResult(); as result) { + showing "{{ result.query }}": {{ result.titles.length }} matches + } @else { + waiting for a search + } +
+
+

+ mergeMap ends on "s", the stale answer that arrived last. switchMap shows what you typed. +

+
+ +

+ In a real search box you'd add debounceTime(300) before the + switchMap, so most keystrokes never send a request at all. Then + distinctUntilChanged() skips a request when the text didn't really change. + Debouncing reduces the race; only switchMap removes it. +

+ +

Expert

+

+ Interceptors. Every request this site makes goes through + retryTransientErrors, a functional interceptor. A GET that fails with a + network error or a 5xx gets two more tries, 400ms and then 800ms later. Before this, one + blip showed the Projects app's error state. +

+ + +

+ retry() works by resubscribing, and resubscribing to a cold HTTP Observable + sends the request again. That's also why the interceptor skips anything that isn't a + GET: a retried POST is a second order, a second payment, a second email. +

+
+

+ Hot vs cold. Cold Observables start fresh work per subscriber (HTTP, + timer). Hot ones share one source (DOM events, a Subject). + BehaviorSubject holds a current value and was the store pattern before + signals. shareReplay({ bufferSize: 1, refCount: true }) makes a cold + stream shared and cached. Leave out refCount and it never unsubscribes from + the source. +

+

+ Testing streams. The demo's operator is covered by marble tests. + TestScheduler runs every RxJS timer in virtual time and asserts exactly when + each value arrives. The interceptor uses HttpTestingController with fake + timers instead. +

+ + +

Pitfalls

+ +

+ Nested subscribes. A subscribe inside a subscribe can't be cancelled + and can't be composed. Use a higher-order operator instead. +

+
+ +

+ catchError on the outer stream kills it. After one failed + search, the box stops searching forever. Catch inside the switchMap, on + the inner request, and return a fallback. +

+
+ +

+ Forgetting to unsubscribe from long-lived streams (intervals, router + events, websockets) leaks memory and runs callbacks on destroyed components. Use + toSignal(), or takeUntilDestroyed() for a manual subscribe. + HTTP calls complete on their own, but they aren't cancelled unless you unsubscribe. +

+
+ +

+ Subscribing twice to an HttpClient call sends two requests. In a + template that's two async pipes on the same Observable. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-note { + font-size: 12px; + } + .race-results { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 8px; + } + .race-result { + display: flex; + flex-direction: column; + padding: 8px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.2)); + border-radius: 8px; + } + .lesson-table { + width: 100%; + border-collapse: collapse; + margin: 12px 0; + font-size: 13px; + } + .lesson-table caption { + text-align: left; + font-weight: 600; + margin-bottom: 4px; + } + .lesson-table th, + .lesson-table td { + text-align: left; + padding: 6px 8px; + border-bottom: 1px solid var(--border-primary, rgba(255, 255, 255, 0.15)); + vertical-align: top; + } + `, +}) +export class Lesson06Rxjs { + protected readonly query = signal(''); + + // toObservable turns the signal into a stream, the operators do the + // over-time work, and toSignal turns it back into something the template + // can read. The subscription ends when the component does. + private readonly queries = toObservable(this.query).pipe(filter((query) => query.length > 0)); + protected readonly mergeResult = this.race('mergeMap'); + protected readonly switchResult = this.race('switchMap'); + + private race(strategy: SearchStrategy) { + return toSignal(this.queries.pipe(searchAsYouType(strategy, slowSearch)), { initialValue: null }); + } + + protected valueOf(event: Event): string { + return (event.target as HTMLInputElement).value; + } + + protected readonly snippets = { + consume: `// Preferred: a signal, unsubscribed automatically on destroy +readonly repos = toSignal(this.http.get('/api/repos'), { initialValue: [] }); + +// Older templates: the async pipe, also unsubscribes for you +repos$ = this.http.get('/api/repos'); +@for (repo of repos$ | async; track repo.id) { ... }`, + race: `export function searchAsYouType( + strategy: 'mergeMap' | 'switchMap', + search: (query: string) => Observable, +): OperatorFunction { + return strategy === 'switchMap' ? switchMap(search) : mergeMap(search); +} + +// in the component +private readonly queries = toObservable(this.query).pipe(filter((q) => q.length > 0)); +protected readonly switchResult = toSignal( + this.queries.pipe(searchAsYouType('switchMap', slowSearch)), + { initialValue: null }, +);`, + interceptor: `export const retryTransientErrors: HttpInterceptorFn = (req, next) => { + if (req.method !== 'GET') return next(req); // only retry what's safe to repeat + + return next(req).pipe( + retry({ + count: 2, + delay: (error, retryCount) => + isTransient(error) // status 0 or 5xx + ? timer(400 * 2 ** (retryCount - 1)) // 400ms, then 800ms + : throwError(() => error), // a 404 fails straight away + }), + ); +}; + +// app.config.ts +provideHttpClient(withFetch(), withInterceptors([retryTransientErrors])),`, + marbles: `scheduler.run(({ hot, expectObservable }) => { + const typed = hot('a 9ms b', { a: 'a', b: 'ab' }); // 'a' at 0ms, 'ab' at 10ms + + // 'ab' answers at 30ms; the 100ms answer for 'a' still lands after it + expectObservable(typed.pipe(searchAsYouType('mergeMap', search))) + .toBe('30ms x 69ms y', { x: 'results for ab', y: 'results for a' }); + + // switchMap cancelled 'a' the moment 'ab' arrived + expectObservable(typed.pipe(searchAsYouType('switchMap', search))) + .toBe('30ms x', { x: 'results for ab' }); +});`, + }; + + protected readonly interview = [ + { + q: 'switchMap, mergeMap, concatMap, exhaustMap: when do you use each?', + a: 'All four map a value to an inner Observable. switchMap cancels the previous inner stream, so use it when only the latest matters: search, route params. mergeMap runs them in parallel, for independent work. concatMap queues them in order, for writes that must not interleave. exhaustMap ignores new values while one is running, for a submit button double-click or a login request.', + }, + { + q: 'What is the difference between a hot and a cold Observable?', + a: 'A cold Observable starts its work separately for each subscriber: every subscribe to an HttpClient call sends a request. A hot one shares a single source that runs regardless, like DOM events or a Subject. You make a cold one shared with share() or shareReplay().', + }, + { + q: 'How do you avoid memory leaks with subscriptions in Angular?', + a: "Mostly by not subscribing manually: toSignal() and the async pipe unsubscribe when the component is destroyed. For a manual subscribe, use takeUntilDestroyed(), which takes a DestroyRef from the injection context. Streams that complete on their own, like a single HTTP call, don't leak, but they aren't cancelled either unless you unsubscribe.", + }, + { + q: 'Subject, BehaviorSubject, ReplaySubject?', + a: 'A Subject is both an Observable and an Observer: you push values in with next() and subscribers get them from then on. BehaviorSubject requires an initial value and gives new subscribers the current one immediately, which made it the service-store pattern before signals. ReplaySubject replays the last N values to late subscribers.', + }, + { + q: 'What is an HTTP interceptor, and what have you used one for?', + a: 'A function in the HttpClient pipeline that sees every request and its response Observable. Typical uses: adding auth headers, retrying, logging, turning errors into user messages, and caching. On my site one retries GETs that fail with a network error or 5xx, with exponential backoff, and never retries POSTs, because those are not safe to repeat.', + }, + { + q: 'Signals or RxJS?', + a: 'Both, at different jobs. Signals hold state that the UI reads synchronously. RxJS models events over time: debouncing, cancellation, retries, combining streams. A common shape is signal input, then toObservable, then the operators, then toSignal back out for the template.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 64aeb86..a852a5a 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -16,4 +16,5 @@ export const LESSON_PAGES: Record Promise>> = { import('./lesson-03-templates').then((m) => m.Lesson03Templates), 'angular-04-signals': () => import('./lesson-04-signals').then((m) => m.Lesson04Signals), 'angular-05-dependency-injection': () => import('./lesson-05-di').then((m) => m.Lesson05Di), + 'angular-06-rxjs': () => import('./lesson-06-rxjs').then((m) => m.Lesson06Rxjs), }; diff --git a/src/app/thoughts-content/lessons/search-race.ts b/src/app/thoughts-content/lessons/search-race.ts new file mode 100644 index 0000000..972afc6 --- /dev/null +++ b/src/app/thoughts-content/lessons/search-race.ts @@ -0,0 +1,20 @@ +import { mergeMap, Observable, OperatorFunction, switchMap } from 'rxjs'; + +export type SearchStrategy = 'mergeMap' | 'switchMap'; + +/** + * [ng-06 rxjs] The operator behind lesson 06's race demo. Both strategies map + * each query to an inner search Observable. They differ in what happens to a + * search still in flight when the next query arrives: + * + * - mergeMap keeps it running, so responses arrive in whatever order the + * server finishes them, and a slow stale one can land last. + * - switchMap unsubscribes from it. For HttpClient, unsubscribing aborts the + * request, so the stale response never arrives at all. + */ +export function searchAsYouType( + strategy: SearchStrategy, + search: (query: string) => Observable, +): OperatorFunction { + return strategy === 'switchMap' ? switchMap(search) : mergeMap(search); +} diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index b957ede..0ccb002 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -259,4 +259,7 @@ The same pass turned the dock's state into a proper store. Two other files had e 'angular-05-dependency-injection': `Four lessons in, the guide needed a way to remember where I'd got to. A "mark complete" toggle needs storage, the site is prerendered, and the server has no localStorage. The settings service already solved that with an isPlatformBrowser check, written out twice. A second feature needing the same check felt like the moment to fix the pattern instead of copying it. So storage became an injection token. One factory decides what storage means on each platform. Both services ask for the token, and the specs hand in an in-memory version instead of clearing the real one. The toggle is at the bottom of this page.`, + 'angular-06-rxjs': `Signals took over most of what I used RxJS for, which made it easier to see what RxJS is still for: things that happen over time. A search box where the answers can come back out of order. A request that fails once and would have worked a second later. + +The second one was a real gap. The Projects app showed its error state on the first network blip. Now every GET goes through a small interceptor that retries transient failures twice with backoff, and never retries anything that isn't safe to send twice. The demo below is the first one: two search boxes over the same slow server, one with mergeMap and one with switchMap.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 1045ba2..50d45a5 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -233,4 +233,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'dependency-injection', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-06-rxjs', + title: 'Angular 06: RxJS and HTTP', + date: '2026-11-21', + summary: + 'Observables, the four higher-order mapping operators, interceptors and marble tests, with a live switchMap vs mergeMap race. Built while making the site retry requests that fail for a moment.', + tags: ['angular-guide', 'rxjs', 'angular'], + relatedApp: 'projects', + }, ]; From f2aa52969f14ddee2abf926c95815e94cf526dba Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:11:13 -0500 Subject: [PATCH 4/4] Bump to 1.4.5 with the lesson 06 changelog entry --- CHANGELOG.md | 6 ++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 788c695..74a8069 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.5 + +- **GET requests retry transient failures.** One network blip used to put the Projects app straight into "Failed to load projects". A functional interceptor, `retryTransientErrors`, now retries any GET that fails with a network error (status 0) or a 5xx, twice, 400ms and then 800ms later. A 404 fails straight away, and nothing but GETs is ever retried, because a retried POST is a second submission +- **Angular guide, lesson 06: RxJS and HTTP** (`/thoughts/angular-06-rxjs`). The live demo runs two search boxes over a deliberately slow fake server, where one-letter queries answer slowest. Type "sig" and mergeMap ends on the stale "s" results while switchMap shows "sig". The operator behind it has marble tests on `TestScheduler` +- Initial bundle 384.98 kB → 389.82 kB. I measured the parts: without the interceptor it's 389.00 kB, and without lesson 06 registered it's 388.39 kB. RxJS's timer and async-scheduler code is shared by the interceptor's backoff and the lesson's `delay`, so it lands in an eager chunk either way. I tried writing the demo with `timer` instead of `delay`, and it saved 0.26 kB, not enough to beat the more readable version. That leaves 10 kB of headroom, so the remaining lessons have to stay out of eager code + ## 2026-11-21 - version 1.4.4 - **Saved reading progress for the Angular guide**: every lesson ends with a "Mark lesson complete" toggle (a real `aria-pressed` button whose label changes too, so the state isn't colour alone). The series nav counts "N of M complete", and the Thoughts list badges completed lessons. Progress is kept in localStorage diff --git a/package-lock.json b/package-lock.json index 5195c24..3944857 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.4", + "version": "1.4.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.4", + "version": "1.4.5", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index db931f8..7f5a6cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.4", + "version": "1.4.5", "scripts": { "ng": "ng", "start": "ng serve",