Promise与Rxjs的区别

promise 代码

let promise = new Promise( (resolve) => {
      setTimeout(() => {
          resolve('chen');
      },2000)
    });
    promise.then((value) => {
      console.log(value);
    })

Rxjs代码

let start = new Observable( (observer) => {
      let timeOut = setTimeout( () => {
        observer.next('chen2');
      },4000)
      
    })
    let str = start.subscribe( (value) => {
      console.log(value);
    })

区别1: rxjs可以取消subscribe,promise不可以

setTimeout( () => {
       str.unsubscribe();
   },1000)

区别2: rxjs可以发射多次,promise只能发射一次

let setTime2;
    let start2 = new Observable( (observable) => {
      let count = 0;
      setTime2 = setInterval( () => {
        observable.next(count++);
      },1000)
    })
    let str2 = start2.subscribe( (num) => {
        console.log(num);
        if(num > 10){
          str2.unsubscribe();
          clearInterval(setTime2);
        } 
    })

区别3: rxjs 自带了许多的工具函数,如filter等

上一篇:Java正则使用


下一篇:Java开发 之小数点保留后两位、千分位符、实数正则校验