RxJS: MergeMap with Preserving Input order

后端 未结 3 1032
悲哀的现实
悲哀的现实 2021-01-07 03:04

Requirement:

urls = [url1, url2, url3]

Fire all 3 urls parallely and paint the Dom in the sequnce of the urls list

 ex: Fini         


        
3条回答
  •  囚心锁ツ
    2021-01-07 03:52

    I couldn't find anything that preserves the order so I came up with something a bit convoluted.

    const { concat, of, BehaviorSubject, Subject } = rxjs;
    const { delay, filter } = rxjs.operators;
    
    const parallelExecute = (...obs$) => {
      const subjects = obs$.map(o$ => {
        const subject$ = new BehaviorSubject();
        const sub = o$.subscribe(o => { subject$.next(o); });
        return { sub: sub, obs$: subject$.pipe(filter(val => val)) };
      });
      const subject$ = new Subject();
      sub(0);
      function sub(index) {
        const current = subjects[index];
        current.obs$.subscribe(c => {
          subject$.next(c);
          current.obs$.complete();
          current.sub.unsubscribe();
          if (index < subjects.length -1) {
            sub(index + 1);
          } else {
            subject$.complete();
          }
        });
      }
      return subject$;
    }
    
    
    parallelExecute(
      of(1).pipe(delay(3000)),
      of(2).pipe(delay(2000)),
      of(3).pipe(delay(1000))
    ).subscribe(result => { console.log(result); });

提交回复
热议问题