RxJS:保留输入顺序的 MergeMap [英] RxJS: MergeMap with Preserving Input order

查看:38
本文介绍了RxJS:保留输入顺序的 MergeMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求:

urls = [url1, url2, url3]

urls = [url1, url2, url3]

并行触发所有 3 个 url 并在 urls 列表的序列中绘制 Dom

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

 ex: Finished order of urls = [url3, url1, url2]
     when url1 finishes Immediately render the DOM, without waiting for url2
     If url2, url3 finishes before url1, then store url2, url3 and paint the DOM after url1 arrives
     Paint the DOM with order [url1, url2, url3]

我使用 Promise 的工作:

// Fired all 3 urls at the same time
p1 = fetch(url1)
p2 = fetch(url2)
p3 = fetch(url3)

p1.then(updateDom)
  .then(() => p2)
  .then(updateDom)
  .then(() => p3)
  .then(updateDom)

我想在 Observables 中做同样的事情.

I wanted to do the same thing in Observables.

from(urls)
  .pipe(
      mergeMap(x => fetch(x))
  )

为了并行触发它们,我使用了合并映射,但是如何对结果的顺序进行排序?

To fire them parallely I used merge map, but how can I order the sequence of the results?

推荐答案

我找不到任何可以保留顺序的东西,所以我想出了一些令人费解的东西.

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); });

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

这篇关于RxJS:保留输入顺序的 MergeMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆