美文网首页
04RxJS创建+合并类操作符

04RxJS创建+合并类操作符

作者: learninginto | 来源:发表于2021-01-04 10:04 被阅读0次
    combineLatest

    合并多个Observable,并返回每个Observable的最新值,必须要每个Observable都有发出值,combineLatest才能被订阅

    import {combineLatest, timer} from 'rxjs'
    const firstTimer = timer(0, 1000);
    const secondTimer = timer(5000, 1000);
    const combinedTimers = combineLatest(firstTimer, secondTimer)
    combinedTimers.subscribe(value => console.log(value))
    

    5秒后第二个流secondTimer发出第一个值,此时的第一个流firstTimer的值为4,所以combineLatest第一个订阅的值是[4,0]

    concat

    类似数组的concat,将每个Observable拼接起来,按顺序发出值

    const timer$ = interval(1000).pipe(take(4));
    //将无限的定时器发送值,通过take只取前成4个流
    const sequence$ = range(1, 10);
    //从1开始,发送10个数值
    const result = concat(timer$, sequence$);
    result.subscribe(x => console.log(x));
    
    forkJoin

    类似Promise.all,在每个Observables都完成后,合并它们发出的最后一个值

    const observable = forkJoin([
      of(1, 2, 3, 4),
      Promise.resolve(8),
      timer(3000),
    ]);
    observable.subscribe({
      next: value => console.log(value),
      complete: () => console.log('This is how it ends'),
    })
    

    3秒后合并发送流,打印[3,8,0]

    merge

    与cancat不同,merge是把值按发射的顺序,逐个进行融合

    const click$ = fromEvent(document, 'click');
    const timer$ = interval(1000);
    const clicksOrTimer = merge(click$, timer$);
    clicksOrTimer.subscribe(x => console.log(x))
    

    单击事件和定时器的流穿插发送

    • 设置最多合并几个Observable

    最后一个参数设为2,表示不管合并了多少个流,merge最多也只能合并两个,与参数顺序无关

    const timer1 = interval(1000).pipe(take(10), mapTo('a'));
    const timer2 = interval(2000).pipe(take(6), mapTo('b'));
    const timer3 = interval(500).pipe(take(10), mapTo('c'));
    const merged = merge(timer1, timer2, timer3, 2);
    merged.subscribe(x => console.log(x));
    
    partition

    将一个Observable流按条件分成两个

    const observalbeValues = of(1, 2, 3, 4);
    const [evens$, odds$] = partition(observalbeValue, value => value % 2=== 0);
    odds.subscribe(x => console.log('odds', x))
    
    //odds 1
    //odds 3
    //evens 2
    //evens 4
    
    race

    类似Promise.race,在多个Observable中,持续推送最快发出值的那个

    const obs1 = interval(1000).pipe(mapTo('fast one'))
    const obs2 = interval(3000).pipe(mapTo('medium one'))
    const obs3 = interval(5000).pipe(mapTo('slow one'))
    race(obs1, obs2, obs3).subscribe(winner => console.log(winner))
    

    fase one……

    zip

    合并多个Observable,会严格按照发射值的位置(索引),合并每个流发出的值

    const obs1 = of<number>(1, 2);
    const obs2 = of<string>('one', 'two')
    zip(obs1, obs2).subscribe(x => console.log(x))
    // [1, "one"]
    // [2, "two"]
    

    相关文章

      网友评论

          本文标题:04RxJS创建+合并类操作符

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