我正在尝试实现这个大理石图,其中hipotesis具有N个sN $,并且我将这些流添加到主$。
s1$ +--1--------------------99--------------------->
s2$ +------3--------7------------------------------>
main$ +---[1]-[1, 3]---[1, 7]---[99, 7]-------------->
现在我有一个aproximation,但是有了“重复”
const main$ = new Rx.Subject()
const s1$ = new Rx.Subject()
const s2$ = new Rx.Subject()
main$
.scan((a, c) => [...a, c], [])
.subscribe(v => console.log(v))
s1$.subscribe(x => main$.onNext(x))
s2$.subscribe(x => main$.onNext(x))
s1$.onNext(3)
s2$.onNext(1)
s1$.onNext(6)
s2$.onNext(44)
/*
Expect:
[3]
[3, 1]
[6, 1]
[6, 44]
*/
/*
What I have:
[3]
[3, 1]
[3, 1, 6]
[3, 1, 6, 44]
*/
有办法做到这一点吗? 我还尝试将流sN $添加到主$:
中const main$ = new Rx.Subject()
const s1$ = new Rx.Subject()
const s2$ = new Rx.Subject()
main$
.mergeAll()
.scan((a, c) => [...a, c], [])
.subscribe(
(v) => console.log(v)
)
main$.onNext(s1$)
main$.onNext(s2$)
s1$.onNext(3)
s2$.onNext(1)
s1$.onNext(6)
s2$.onNext(44)
答案 0 :(得分:1)
您可以使用combineLatest。虽然仍然需要每个流都以值开头,但您可以在null
前加上前缀,以使每个流都使用startWith开头。
const source = Rx.Observable.combineLatest(
s1.startWith(void 0),
s2.startWith(void 0),
s3.startWith(void 0),
(s1, s2, s3) => [s1, s2, s3])
可选您可以从结果数组中删除undefined
值。
现在,我们可以扩展它以使用变量的流列表。致@xgrommx。
main$
.scan((a, c) => a.concat(c), [])
.switch(obs => Rx.Observable.combineLatest(obs))
我们还可以使用c.shareReplay(1)
在我们switch
时让流记住最后一个值。但是,这不会与c.startWith(void 0)
结合使用,因此我们可以使用其中一种。
示例:
const main$ = new Rx.Subject()
const s1$ = new Rx.Subject(1)
const s2$ = new Rx.Subject(1)
const s3$ = new Rx.Subject(1)
const s4$ = new Rx.Subject(1)
main$
.scan((a, c) => a.concat(c.shareReplay(1)), [])
.map(obs => Rx.Observable.combineLatest(obs))
.switch()
.map(v => v.filter(e => !!e))
.map(v => v.join(','))
.subscribe(v => $('#result').append('<br>' + v))
main$.onNext(s1$)
s1$.onNext(1)
main$.onNext(s2$)
s2$.onNext(void 0) // Since we can't use startWith
main$.onNext(s3$)
s3$.onNext(5)
s1$.onNext(55)
s2$.onNext(12)
s2$.onNext(14)
s3$.onNext(6)
main$.onNext(s4$)
s4$.onNext(999)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
<div id="result"></div>
答案 1 :(得分:0)
我最后通过一些过滤我在startWith()
上开始的空值来解决问题:
main$
.scan((a, c) => [...a, c.startWith(null).shareReplay(1)], [])
.map(obs => Observable.combineLatest(obs))
.switch()
.map((x) => x.filter((x) => x != null))
.filter((x) => x.length)
看起来不可读(如任何Rx序列,但如果你画出大理石就完全有意义了!)