异步编程:rxjs入门到精通

一、常见的异步编程有

  • 1、回调函数
  • 2、promise
  • 3、事件监听/发布订阅
  • 4、rxjs

二、使用promiserxjs实现异步编程的对比

  • 1、使用promise异步编程的写法

    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('promise成功了');
      }, 1000);
    });
    
    promise.then(data => {
      console.log(data);
    });
    
  • 2、使用rxjs异步流编程的写法

    import { Observable } from 'rxjs';
    const stream = new Observable(observer => {
      setTimeout(() => {
        observer.next('rxjs成功了');
      });
    });
    stream.subscribe(data => {
      console.log(data);
    });
    

二、rxjs可以取消订阅,但是promise却不可以

  • 1、具体实现代码

    import { Observable } from 'rxjs';
    
    const stream = new Observable(observer => {
      setTimeout(() => {
        observer.next('请求成功');
      }, 2000);
    });
    
    const disposable = stream.subscribe(data => {
      console.log(data);
    });
    
    setTimeout(() => {
      disposable.unsubscribe(); // 取消订阅
    }, 1000);
    

三、异步多次执行

对于promise的执行是一个状态到另外一个状态后是不可变的,结果要不是resole就是reject,但是不能回退

  • 1、在promise中的定时器【只执行一次】

    const promise = new Promise((resolve, reject) => {
      setInterval(() => {
        resolve('promise成功了');
      }, 1000);
    });
    
    promise.then(data => {
      console.log(data);
    });
    
  • 2、使用rxjs多次执行

    import { Observable } from 'rxjs';
    
    const stream = new Observable(observer => {
      let count: number = 0;
      setInterval(() => {
        observer.next(count++);
      }, 1000);
    });
    
    const disposable = stream.subscribe(data => {
      console.log(data);
    });
    

四、常见的操作符

  • 1、使用方式

    import { Observable } from 'rxjs';
    import { map, filter } from 'rxjs/operators';
    
    const stream =
      new Observable() <
      number >
      (observer => {
        let count = 0;
        setInterval(() => {
          observer.next(count++);
        }, 1000);
      });
    
    stream
      .pipe(
        filter((x: number) => x % 2 === 0),
        map((x: number) => x * 2)
      )
      .subscribe(data => {
        console.log(data);
      });
    
  • 2、常见的操作符见官网地址

    • Creation Operators创建异步流的操作符号
    • Join Creation Operators连接创建
    • Transformation Operators数据转换的
    • Filtering Operators过滤数据
    • Join Operators连接的操作符
    • Multicasting Operators
    • Error Handling Operators
    • Utility Operators
    • Conditional and Boolean Operators
    • Mathematical and Aggregate Operators
  • 3、比如限制点击评率的过滤管道

    import { fromEvent } from 'rxjs';
    import { throttleTime } from 'rxjs/operators';
    
    const clicks = fromEvent(document, 'click');
    // 限制1000ms内不能重复点击
    const result = clicks.pipe(throttleTime(1000));
    result.subscribe(x => console.log(x));
    
上一篇:final、finalize和 finally 的不同之处?


下一篇:MOBX在项目开发中的具体使用