操作符参考
本页汇总了用于创建、转换、过滤和组合流的常用函数。可使用 pipeFrom 函数组合操作符。
创建操作符
用于创建相关处理的操作符。
from
from<T>(create: () => T): Sub<T>
从同步工厂函数创建流。
示例:
const lazy$ = from(() => Math.random());
const greeting$ = from(() => 'hello');创建
fromPromise
fromPromise<T>(create: () => Promise<T>): Sub<T>
从 Promise 工厂函数创建流。
示例:
const request$ = fromPromise(() => fetch('/api/data'));
request$(console.log);创建
of
of<T>(...values: T[]): Sub<T>
创建按顺序发出给定值的流。
示例:
const stream$ = of(1, 2, 3);
stream$(console.log); // Emits: 1, 2, 3创建
interval
interval(period: number): Sub<number>
创建按指定间隔发出连续数字的流。
示例:
const timer$ = interval(1000);
timer$(console.log); // Emits: 0, 1, 2, ... every second创建
使用模式
基础组合
所有操作符都可以与 pipeFrom 函数配合使用:
import { pipeFrom, from, map, filter, take } from 'rx4u';
const result$ = pipeFrom(
of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
filter(x => x % 2 === 0), // Keep even numbers
map(x => x * x), // Square them
take(3) // Take first 3
); // Emits: 4, 16, 36错误处理模式
const resilientStream$ = pipeFrom(
riskyOperation$,
retry(3),
catchError(error => {
console.error('Operation failed:', error);
return of('fallback value');
})
);异步操作
const searchResults$ = pipeFrom(
searchInput$,
debounceTime(300), // Wait for user to stop typing
distinctUntilChanged(), // Skip duplicate queries
switchMap(query => // Switch to new search
fromPromise(() => fetch(`/api/search?q=${query}`))
),
catchError(err => of([)) // Return empty on error
);