美文网首页
05RxJS高阶Observable

05RxJS高阶Observable

作者: learninginto | 来源:发表于2021-01-05 09:53 被阅读0次

    高阶的Observale,一个Observalbe还嵌套着其它的Observale

    combineAll

    高阶转低阶,等到Observable完成后,对收集到的observalbes使用combineLatest

    const clicks = fromEvent(document, 'click');
    const higherOrder = clicks.pipe(map(ev => interval(1000).pipe(take(2))),
      take(3)
      // 控制数字中有几个流
    )
    const result = higherOrder.pipe(combineAll())
    // combineAll必须要等高阶的流全部完成才能被订阅(点击两次才完成),每次会把点击发出的值用combineLatest策略合并点击的最新值
    result.subscribe(x => console.log(x))
    
    concatAll

    高阶转低阶,按顺序订阅每一个Observable

    const clicks = fromEvent(document, 'click');
    const higherOrder = clicks.pipe(map(ev => interval(1000).pipe(take(4))),
    )
    const result = higherOrder.pipe(concatAll())
    result.subscribe(x => console.log(x))
    

    每次点击都转换成只有四个值(0,1,2,3)的定时器

    mergeAll

    有流就发,没有顺序

    const clicks = fromEvent(document, 'click');
    const higherOrder = clicks.pipe(map(ev => interval(1000)),
    )
    const result = higherOrder.pipe(mergeAll())
    result.subscribe(x => console.log(x))
    

    每次点击都产生新的流,每个定时器之间的值互不影响。

    startWith和endWith
    • startWith:在Observable发射值之前,先发射一个指定的值
    • endWith:在Observalbe完成后,再发射一个指定的值
    of('from source ').pipe(startWith('first'), endWith('end'))
      .subscribe(x => console.log(x))
    //first
    //from source 
    //end
    
    withLatestFrom

    类似combinelatest,不过它只保证第二个流的值是最新的

    从点击的事件中取出当前点击位置的横坐标,

    const click = fromEvent(document, 'click').pipe(pluck('clientX'))
    const interval$ = interval(1000);
    const result = click.pipe(withLatestFrom(interval$))
    result.subscribe(x => console.log(x))
    

    将click和interval$的位置替换,不管过多久,直到点击之后定时器才被触发

    const click = fromEvent(document, 'click').pipe(pluck('clientX'))
    const interval$ = interval(1000);
    const result = interval$.pipe(withLatestFrom(click))
    result.subscribe(x => console.log(x))
    

    相关文章

      网友评论

          本文标题:05RxJS高阶Observable

          本文链接:https://www.haomeiwen.com/subject/xadioktx.html