Configs2026年4月11日·1 分钟阅读

RxJS — Reactive Programming Library for JavaScript

RxJS is a reactive extensions library for JavaScript using Observables for composing asynchronous and event-based programs. 100+ operators for transforming, filtering, and combining streams. The foundation of Angular and many complex UIs.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

npm i rxjs
import { fromEvent, map, debounceTime, switchMap, from } from "rxjs";

const search = document.getElementById("search") as HTMLInputElement;

const results$ = fromEvent(search, "input").pipe(
  map((e) => (e.target as HTMLInputElement).value),
  debounceTime(300),
  switchMap((q) => from(fetch(`/api?q=${q}`).then((r) => r.json())))
);

results$.subscribe((data) => console.log(data));
介绍

RxJS is the JavaScript implementation of the Reactive Extensions (ReactiveX) API — a library for composing asynchronous and event-based programs using Observable sequences. Originally developed at Microsoft and ported to many languages. In JS land, it powers Angular internals, NgRx, and complex reactive UIs.

What RxJS Does

  • Observable — lazy stream of values over time
  • Operators — 100+ composable transforms (map, filter, merge, concat, switchMap, debounce, throttle)
  • Subject — multicast observable, act as source and consumer
  • Schedulers — control when subscriptions execute
  • Error handling — catchError, retry, retryWhen
  • Backpressure — sampling, throttling, buffering strategies
  • TypeScript — full typing including operator inference

Architecture

Observables are lazy: they start producing values only when subscribed. Operators are pure functions that return new Observables. Pipeline compiles via the pipe() helper. Schedulers let you move work to microtask/animation frame/etc.

Self-Hosting

Library only.

Key Features

  • 100+ operators
  • Lazy by default
  • Cancellable subscriptions
  • Multiple subject types (BehaviorSubject, ReplaySubject, AsyncSubject)
  • Schedulers for timing control
  • Error handling pipeline
  • Tree-shakeable imports
  • Full TypeScript types

Comparison

Library Model Learning Curve Use Case
RxJS Observable streams Steep Complex async, Angular
Effect Fiber-based Medium FP-heavy TS projects
XState State machines Medium Stateful flows
Async iterators Pull-based Easy Simple streams
Signals Reactive primitives Easy Fine-grained UI updates

常见问题 FAQ

Q: Promise 已经够用了? A: Promise 是单值,RxJS 是多值流(事件序列、轮询、推送通知)。且 RxJS 支持取消订阅(Promise 不行)。

Q: 学习曲线陡? A: 最难的是掌握 100+ 操作符。建议先学 map/filter/switchMap/mergeMap/debounceTime/catchError 这 6 个够日常用。

Q: Angular 为什么深度用 RxJS? A: Angular 的 HttpClient、Router、Reactive Forms、EventEmitter 都返回 Observable。RxJS 是 Angular 生态一等公民。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产