开始使用 rx4u
rx4u 是面向 JavaScript 和 TypeScript 的函数式响应式编程库,是轻量、纯函数的 RxJS 替代方案。本指南将帮助你快速上手。
安装
使用喜欢的包管理器安装 rx4u:
npm install rx4upnpm add rx4uyarn add rx4u快速开始
以下是一个帮助你开始使用 rx4u 的简单示例:
import { of, pipeFrom, map, filter, take } from 'rx4u';
// Create a stream from values
const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Apply operators using pipeFrom
const result$ = pipeFrom(
numbers$,
filter(x => x % 2 === 0), // Only even numbers
map(x => x * 2), // Double each number
take(3) // Take only first 3 results
);
// Subscribe to the stream
result$(
value => console.log('Next:', value), // 4, 8, 12
error => console.error('Error:', error),
() => console.log('Complete!')
);核心概念
1. 函数式方法
不同于 RxJS 的面向对象方法,rx4u 使用纯函数:
RxJS (面向对象)
observable.pipe(
map(x => x * 2),
filter(x => x > 5)
)rx4u (函数式)
pipeFrom(stream$,
map(x => x * 2),
filter(x => x > 5)
)2. 惰性执行
rx4u 流采用惰性执行,只有订阅后才会执行:
const stream$ = pipeFrom(
from(() => {
console.log('Factory called!'); // Only when subscribed
return [1, 2, 3];
}),
map(x => {
console.log('Processing:', x); // Only runs when subscribed
return x * 2;
})
);
// Nothing happens yet...
stream$(console.log); // Now the processing starts3. 简单的订阅模型
rx4u 为订阅提供简单的函数签名。每次调用都会返回一个取消订阅函数:
const unsubscribe = stream$(
next, // (value: T) => void
error, // (error: unknown) => void [optional]
complete // () => void [optional]
);
// Clean up when done
unsubscribe();4. 独立订阅
默认情况下,每次订阅都会创建独立的执行:
const random$ = from(() => Math.random());
random$(x => console.log('Sub 1:', x)); // Different value
random$(x => console.log('Sub 2:', x)); // Different value
// Use share() to share a single execution:
import { share } from 'rx4u';
const sharedRandom$ = pipeFrom(random$, share());
sharedRandom$(x => console.log('Shared 1:', x)); // Same value
sharedRandom$(x => console.log('Shared 2:', x)); // Same value流创建函数
rx4u 提供多种创建流的方式:
from() - 从工厂函数创建
from(() => Math.random())
from(() => crypto.randomUUID())fromPromise() - 从 Promise 工厂创建
fromPromise(() => fetch('/api/data'))of() - 从单个值创建
of(1, 2, 3, 4, 5)
of('a', 'b', 'c')interval() - 定时器流
interval(1000) // 0, 1, 2, ... every second
interval(500) // 0, 1, 2, ... every 500msfromEvent() - DOM 事件
fromEvent(button, 'click')
fromEvent(input, 'input')TypeScript 支持
rx4u 使用 TypeScript 构建,提供出色的类型安全:
import { of, pipeFrom, map, filter } from 'rx4u';
const numbers$ = of(1, 2, 3, 4, 5); // Sub<number>
const strings$ = pipeFrom(
numbers$,
filter(x => x > 2), // Still Sub<number>
map(x => x.toString()) // Now Sub<string>
);
strings$(
value => console.log(value.toUpperCase()) // TypeScript knows value is string
);下一步
从 RxJS 迁移
如果你正在从 RxJS 迁移,请从上面的示例开始。主要区别是 rx4u 通过 pipeFrom 组合函数。