Paw*_*mar 2 system.reactive rxjs
要求:
urls = [url1, url2, url3]
并行触发所有 3 个 url 并在 urls 列表的序列中绘制 Dom
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]
Run Code Online (Sandbox Code Playgroud)
我的工作使用承诺:
// 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)
Run Code Online (Sandbox Code Playgroud)
我想在 Observables 中做同样的事情。
from(urls)
.pipe(
mergeMap(x => fetch(x))
)
Run Code Online (Sandbox Code Playgroud)
为了并行触发它们,我使用了合并映射,但是如何对结果的顺序进行排序?
像这样的异步任务保持顺序的最佳方法是使用concatMap。
问题是,如果我们单独应用它,我们就会失去并行化。如果我们要做这样的事情:
from(urls)
.pipe(
concatMap(x => fetch(x))
);
Run Code Online (Sandbox Code Playgroud)
在第一个请求完成之前,不会触发第二个请求。
我们可以通过将地图分离成它自己的操作符来解决这个问题:
from(urls)
.pipe(
map(x => fetch(x)),
concatMap(x => x)
);
Run Code Online (Sandbox Code Playgroud)
所有请求都将同时触发,但结果将按请求顺序发出。
请参阅下面适用于使用此方法的Adrian示例:
from(urls)
.pipe(
concatMap(x => fetch(x))
);
Run Code Online (Sandbox Code Playgroud)
from(urls)
.pipe(
map(x => fetch(x)),
concatMap(x => x)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
768 次 |
| 最近记录: |