乐闻世界logo
搜索文章和话题

RxJS 6 和 RxJS 7 有什么区别?

2026年2月21日 16:54

RxJS 6 与 RxJS 7 的主要变化

1. 导入方式的变化

RxJS 6:

javascript
// 创建操作符 import { of, from, interval } from 'rxjs'; // 操作符(使用 pipe) import { map, filter, switchMap } from 'rxjs/operators'; // 工具函数 import { Subscription } from 'rxjs';

RxJS 7:

javascript
// 导入方式基本相同,但更加模块化 import { of, from, interval } from 'rxjs'; import { map, filter, switchMap } from 'rxjs/operators'; // 新增了一些操作符 import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

2. 新增的操作符

RxJS 7 新增了多个有用的操作符:

1. partition

根据谓词函数将 Observable 分成两个。

javascript
import { of, partition } from 'rxjs'; const source$ = of(1, 2, 3, 4, 5, 6); const [evens$, odds$] = partition(source$, x => x % 2 === 0); evens$.subscribe(x => console.log('Even:', x)); // 2, 4, 6 odds$.subscribe(x => console.log('Odd:', x)); // 1, 3, 5

2. tap 的改进

tap 现在接受一个对象,可以分别处理不同的通知类型。

javascript
import { of } from 'rxjs'; import { tap } from 'rxjs/operators'; of(1, 2, 3).pipe( tap({ subscribe: () => console.log('Subscribed'), next: value => console.log('Next:', value), error: error => console.log('Error:', error), complete: () => console.log('Completed'), unsubscribe: () => console.log('Unsubscribed') }) ).subscribe();

3. connectable 操作符

简化了多播 Observable 的创建。

javascript
import { interval, connectable } from 'rxjs'; import { take } from 'rxjs/operators'; const source$ = interval(1000).pipe(take(5)); const connectable$ = connectable(source$); connectable$.subscribe(value => console.log('Subscriber 1:', value)); connectable$.subscribe(value => console.log('Subscriber 2:', value)); connectable$.connect();

4. shareReplay 的改进

shareReplay 现在支持配置对象。

javascript
import { interval } from 'rxjs'; import { shareReplay, take } from 'rxjs/operators'; const shared$ = interval(1000).pipe( take(5), shareReplay({ bufferSize: 2, refCount: true }) );

5. filter 的类型推断改进

更好的 TypeScript 类型推断。

javascript
import { of } from 'rxjs'; import { filter } from 'rxjs/operators'; const source$ = of(1, 2, 3, 4, 5); // RxJS 7 中类型推断更准确 const even$ = source$.pipe( filter(x => x % 2 === 0) // x 被推断为 number ); even$.subscribe(x => console.log(x)); // x 是 number 类型

3. 废弃的操作符

以下操作符在 RxJS 7 中被废弃:

1. throwError

RxJS 6:

javascript
import { throwError } from 'rxjs'; throwError('Error message');

RxJS 7:

javascript
import { throwError } from 'rxjs'; // 推荐使用工厂函数 throwError(() => new Error('Error message'));

2. concatmerge 的静态方法

虽然仍然可用,但推荐使用 concatWithmergeWith

javascript
import { of, concat, merge } from 'rxjs'; // 仍然可用 concat(of(1), of(2)).subscribe(); merge(of(1), of(2)).subscribe(); // 推荐使用 of(1).pipe(concatWith(of(2))).subscribe(); of(1).pipe(mergeWith(of(2))).subscribe();

4. 性能优化

1. 更小的包体积

RxJS 7 通过树摇优化减少了包体积。

javascript
// RxJS 7 只导入需要的操作符 import { of } from 'rxjs'; import { map } from 'rxjs/operators'; // 打包时只会包含 of 和 map

2. 更快的执行速度

某些操作符的执行速度得到了优化。

javascript
import { of } from 'rxjs'; import { map, filter } from 'rxjs/operators'; // RxJS 7 中这些操作符执行更快 of(1, 2, 3, 4, 5).pipe( map(x => x * 2), filter(x => x > 5) ).subscribe();

5. TypeScript 改进

1. 更好的类型推断

javascript
import { of } from 'rxjs'; import { map, filter } from 'rxjs/operators'; // RxJS 7 中类型推断更准确 const result$ = of(1, 2, 3).pipe( map(x => x.toString()), // 推断为 Observable<string> filter(x => x.length > 0) );

2. 严格类型检查

javascript
import { of } from 'rxjs'; import { map } from 'rxjs/operators'; // RxJS 7 中类型检查更严格 of(1, 2, 3).pipe( map(x => x.toUpperCase()) // TypeScript 错误:number 没有 toUpperCase );

6. 错误处理改进

1. 更好的错误信息

javascript
import { of } from 'rxjs'; import { map } from 'rxjs/operators'; of(1, 2, 3).pipe( map(x => { if (x === 2) throw new Error('Custom error'); return x; }) ).subscribe({ error: error => { console.log(error.message); // 更清晰的错误信息 } });

2. onErrorResumeNext 的改进

javascript
import { of, onErrorResumeNext } from 'rxjs'; const source1$ = of(1, 2, 3).pipe( map(x => { if (x === 2) throw new Error('Error'); return x; }) ); const source2$ = of(4, 5, 6); onErrorResumeNext(source1$, source2$).subscribe(console.log); // 输出: 1, 4, 5, 6

7. 调度器改进

1. animationFrameScheduler 的改进

javascript
import { interval, animationFrameScheduler } from 'rxjs'; import { take } from 'rxjs/operators'; // RxJS 7 中 animationFrameScheduler 更稳定 interval(0, animationFrameScheduler).pipe( take(60) ).subscribe(frame => { console.log('Frame:', frame); });

2. asapScheduler 的改进

javascript
import { of, asapScheduler } from 'rxjs'; // RxJS 7 中 asapScheduler 性能更好 of(1, 2, 3, asapScheduler).subscribe(value => { console.log(value); });

8. 测试工具改进

1. TestScheduler 的改进

javascript
import { TestScheduler } from 'rxjs/testing'; // RxJS 7 中 TestScheduler 更易用 const testScheduler = new TestScheduler((actual, expected) => { expect(actual).toEqual(expected); }); testScheduler.run(({ cold, expectObservable }) => { const source$ = cold('-a-b-c|'); const expected = '-a-b-c|'; expectObservable(source$).toBe(expected); });

2. marble testing 的改进

javascript
import { TestScheduler } from 'rxjs/testing'; // RxJS 7 中 marble testing 更直观 testScheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => { const source$ = cold('-a-b-c|'); const expected = '-a-b-c|'; expectObservable(source$).toBe(expected); });

9. 文档和示例改进

1. 更好的文档

RxJS 7 提供了更详细的文档和示例。

javascript
// 官方文档提供了更多实用的示例 import { of } from 'rxjs'; import { map, filter } from 'rxjs/operators'; of(1, 2, 3, 4, 5).pipe( map(x => x * 2), filter(x => x > 5) ).subscribe(console.log);

2. 更多的最佳实践

官方文档中包含了更多的最佳实践建议。

javascript
// 推荐使用 pipe 而不是链式调用 import { of } from 'rxjs'; import { map, filter } from 'rxjs/operators'; // ✅ 推荐 of(1, 2, 3).pipe( map(x => x * 2), filter(x => x > 5) ).subscribe(); // ❌ 不推荐 of(1, 2, 3).pipe( map(x => x * 2) ).pipe( filter(x => x > 5) ).subscribe();

10. 迁移指南

1. 从 RxJS 6 迁移到 RxJS 7

bash
# 升级 RxJS npm install rxjs@7 # 检查废弃的 API npm run lint

2. 常见迁移问题

问题 1: throwError 的使用

javascript
// ❌ RxJS 6 throwError('Error message'); // ✅ RxJS 7 throwError(() => new Error('Error message'));

问题 2: 类型推断问题

javascript
// 可能需要显式类型 import { of } from 'rxjs'; import { map } from 'rxjs/operators'; const result$ = of(1, 2, 3).pipe( map(x => x.toString()) ) as Observable<string>;

总结

RxJS 7 相比 RxJS 6 的主要改进:

  1. 新增操作符: partitionconnectable
  2. 性能优化: 更小的包体积,更快的执行速度
  3. TypeScript 改进: 更好的类型推断和严格类型检查
  4. 错误处理: 更好的错误信息和处理机制
  5. 调度器改进: 更稳定和高效的调度器
  6. 测试工具: 更易用的 TestScheduler
  7. 文档改进: 更详细的文档和示例

迁移到 RxJS 7 可以带来更好的性能和开发体验,但需要注意一些 API 的变化。

标签:Rxjs