AGENT SKILL

ams-rxjs-pro

暂无简介

License 许可
MIT
所属仓库
TanNhatCMS/jarvis
最近更新
2026-11-07
Stars
★ 0
Forks
1

03 SKILL.md 正文

RxJS Pro

A practical guide to RxJS: thinking in observables — streams of values over time — with the operator toolkit (map/filter/scan, flattening strategies, combination, error handling) and the subscription discipline that prevents leaks.

Overview

RxJS models async as streams: user events, HTTP responses, timers, websockets — all observables you compose with operators instead of nesting callbacks or chaining promises imperatively. The power is in composition and cancellation: switchMap cancels stale requests automatically; debounceTime + distinctUntilChanged build search-as-you-type in three operators; combineLatest merges streams declaratively.

When to use

  • Search-as-you-type, autocomplete, typeahead.
  • Websocket streams, live data, polling with backoff.
  • Complex async orchestration (dependent requests, race conditions, cancellation).
  • Angular apps (RxJS is idiomatic there: HttpClient, forms, router events).
  • Event-heavy UIs: drag interactions, multi-source state.

Core concepts

  • Observable. Lazy push collection: new Observable(subscriber => {...}). Cold (each subscription re-executes, e.g., HTTP) vs hot (shared, e.g., Subjects, websocket).
  • Operators. Pure functions composing streams: map, filter, scan (stateful reduce), tap (side effects for debugging), take, first.
  • Flattening (the big one). switchMap (cancel previous — search, route params), mergeMap (concurrent — bulk ops), concatMap (sequential — ordered saves), exhaustMap (ignore while busy — submit buttons, login).
  • Combination. combineLatest (latest from each), withLatestFrom, forkJoin (all complete → one emission), zip, race.
  • Subjects. Subject (multicast), BehaviorSubject (current value + new subscribers get latest), ReplaySubject (buffer). Bridges between imperative and reactive code.
  • Error handling. catchError (recover/replace), retry/retryWhen (transient failures), finalize (cleanup). Errors terminate streams — handle or the stream dies.
  • Subscription management. takeUntil(destroy$), async pipe (Angular auto-unsubscribes), Subscription.add. Unclosed subscriptions = leaks.

Practical workflow

1. Search-as-you-type (the canonical example).

import { fromEvent, debounceTime, distinctUntilChanged, filter, switchMap, catchError, of } from 'rxjs';

fromEvent(input, 'input').pipe(
  map(e => e.target.value.trim()),
  debounceTime(300),
  distinctUntilChanged(),
  filter(q => q.length >= 2),
  switchMap(q => searchApi(q).pipe(catchError(() => of([])))), // cancel stale, survive errors
).subscribe(renderResults);

2. Polling with backoff.

timer(0, 5000).pipe(
  exhaustMap(() => fetchStatus()),   // skip tick if previous still running
  retry({ delay: (err, n) => timer(Math.min(1000 * 2 ** n, 30000)) }),
  takeUntil(stop$),
).subscribe(updateUI);

3. Component lifecycle (Angular).

private destroy$ = new Subject<void>();
ngOnInit() {
  this.route.paramMap.pipe(
    map(p => p.get('id')),
    switchMap(id => this.service.get(id)),
    takeUntil(this.destroy$),
  ).subscribe(...);
}
ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }

Or just use the async pipe in templates — no manual subscription at all.

4. Share expensive streams. source$.pipe(shareReplay({ bufferSize: 1, refCount: true })) — one underlying subscription, late subscribers get the latest.

Common pitfalls

  • Wrong flattening operator. mergeMap for search = out-of-order results; switchMap for saves = lost writes. Choose deliberately: cancel/parallel/sequential/ignore.
  • Unclosed subscriptions. Every .subscribe needs an end: takeUntil, take(1), first(), or async pipe. Route-change leaks are the classic Angular memory bug.
  • Errors killing streams. One unhandled error completes the whole stream silently. catchError at the right level (inside switchMap, not outside the whole pipe, usually).
  • Nested subscribes. obs1.subscribe(v => obs2.subscribe(...)) — callback hell with extra steps. Flatten with operators.
  • Subjects as first resort. Reaching for Subject before trying pure operators creates imperative spaghetti. Subjects bridge; operators compose.
  • combineLatest needs all to emit. It waits for every source's first emission — a never-emitting source stalls the whole combination. Seed with startWith or use BehaviorSubject.
  • Hot vs cold confusion. Subscribing twice to a cold HTTP observable fires two requests. shareReplay when you want one execution, many observers.
  • Over-engineering. Simple one-shot async doesn't need streams. Promises/async-await for single values; RxJS for streams, cancellation, and composition.

04 同仓库更多 Skills

TanNhatCMS
TanNhatCMS/jarvis

web-scrape

Turn web pages into LLM-ready markdown via the Firecrawl API (renders JS, anti-bot handling). Use when browser_open/fetch fails on JS-heavy pages, or when you need clean markdown/structured extraction from a site. Requires FIRECRAWL_API_KEY.

★ 0
TanNhatCMS
TanNhatCMS/jarvis

design-taste-frontend

tasteskill v2, the anti-slop frontend skill. Art direction for websites, distilled from a study of 247 curated gallery sites (One Page Love, Awwwards Sites of the Day). Deals researched directions (idea, composition, type, palette, photographs, section blueprints) from a library, enforces a strict no-slop house style with a real-browser inspector, and runs a look-and-fix loop on screenshots. Use this whenever you build, design, redesign, restyle, polish or review a landing page, marketing site, portfolio, product page, one-pager, hero or any public-facing web page, in any stack (HTML/CSS, React, Next.js, Vue, Svelte, Astro, Tailwind) — also when the user says a page looks generic, templated, "AI-made", sloppy, or asks to make it look designed, premium, award-level or less like every other site. Not for dashboards or app screens.

★ 0
TanNhatCMS
TanNhatCMS/jarvis

test-driven-development

Use when implementing any feature or bugfix, before writing implementation code

★ 0
TanNhatCMS
TanNhatCMS/jarvis

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes

★ 0
TanNhatCMS
TanNhatCMS/jarvis

requesting-code-review

Use when completing tasks, implementing major features, or before merging to verify work meets requirements

★ 0
TanNhatCMS
TanNhatCMS/jarvis

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

★ 0