rxjs
安装
1. web: https://unpkg.com/rxjs@7.8.0/dist/cjs/index.js
2. npm: npm install rxjs 因为rxjs本身就是ts写的,所以没有@types/rxjs 这个类型文件。
github仓库: https://github.com/ReactiveX/rxjs
码云: https://gitee.com/mirrors/rxjs?_from=gitee_search
在webpack中使用rxjs: tsconfig.json 文件中需要配置 "moduleResolution": "node", 否则会报错找不到模块rxjs
在纯粹的typescript中使用rxjs,也需要在tsconfig.json 文件中需要配置 "moduleResolution": "node", 但是虽然不报错,但编译后的js文件却不能正常运行,因为依赖的rxjs代码没有进行打包。
基本使用
1 import { Observable } from "rxjs"; 2 3 const source$ = new Observable(observer => { 4 console.log('start!'); 5 observer.next(1); 6 observer.next(2); 7 observer.complete(); 8 // observer.error({err: 'err'}); 9 return { 10 unsubscribe: () => { 11 console.log('unsubscribe'); 12 } 13 } 14 }); 15 const subscription = source$.subscribe({ 16 next: val => console.log('val=', val), 17 error: err => console.log('err=', err), 18 complete: () => console.log('complete='), 19 }); 20 subscription.unsubscribe();
原理
source$ = new Observer(fn),source$每次被订阅时,均会调用一次fn函数,如果source$不被订阅,则fn函数永远也不可能被执行。
observer一旦调用complete或error方法后,该 Observable对象的状态就被冻结,此后即使再调用next、error、complete 均自动被忽略。
订阅时subscribe()中的next、error、complete 回调是三个独立的通道,不会有数据的重叠。
订阅时subscribe()中的next、error、complete 回调中如果本身有报错,则只影响这个报错的回调,虽然程序会抛出错误,但不影响后序代码的执行(因为rxjs中已经捕捉了错误)。
但是这种报错不会被订阅中的error回调捕捉,error回调中会接收数据源source$中的错误。
fn函数中的错误会被rxjs捕捉,然后以observer.error()传递出来。
订阅时subscribe()中的next、error、complete 任何一个的值均可以传入null或undefined,表示不需要处理这个通道的数据。
end

浙公网安备 33010602011771号