用 undefined 填充 zip() [英] Padding zip() with undefined
本文介绍了用 undefined 填充 zip()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下
Rx.Observable.zip(
Rx.Observable.of(1,2),
Rx.Observable.of("a"))
.subscribe(p => console.log(p))
生产
1,a
这是有道理的,但我想要它产生的是
which makes sense, but what I want it to produce is
1,a
2,undefined
我想用 undefined 填充较短的 observable,直到较长的 observable 完成.有什么建议吗?
I want to pad the shorter observable with undefineds until the longer one completes. Any suggestions?
推荐答案
我认为这其中的关键是确保所有的源 observable 的长度相同.
I think the key to this is to ensure that all of the source observables are the same length.
一种解决方案是编写一个与最长源可观察值一样长的计数器可观察值.然后可以将其连接到较短的源可观察值,如下所示:
One solution would be to compose a counter observable that's as long as the longest source observable. It could then be concatenated to the shorter source observables, like this:
const pad = (...sources) => Rx.Observable.create(observer => {
// Publish the source observables to make them multicast
// and to allow the subscription order to be managed.
const publishedSources = sources.map(source => source.publish());
// Create an observable that emits an incremented index and
// is as long as the longest source observable.
const counter = Rx.Observable
.merge(...publishedSources.map(
source => source.map((unused, index) => index)
))
.scan((max, index) => Math.max(max, index), 0)
.distinctUntilChanged()
.publish();
// Zip the published sources, contatenating the counter so
// that they are all the same length. When the counter
// emissions are concatenated, they are mapped to undefined.
const subscription = Rx.Observable.zip(...publishedSources.map(
source => source.concat(counter.mapTo(undefined))
)).subscribe(observer);
// Connect the counter and the published sources.
subscription.add(counter.connect());
publishedSources.forEach(
source => subscription.add(source.connect())
);
return subscription;
});
pad(
Rx.Observable.of(1, 2),
Rx.Observable.of("a")
).subscribe(padded => console.log(padded));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
这篇关于用 undefined 填充 zip()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文