如何从其他流中的最后一个事件之后的一个流中获取事件

时间:2016-07-27 11:12:03

标签: javascript angular reactive-programming rxjs rxjs5

有两个流永远不会完成:

--a---b-c-d---e--f---->

-----1-------2------3-->

我想从第二个流中的最后一个事件之后的第一个流中获取事件。

一开始它看起来像这样:

--a->
 (?)
---->
 (=)
--a->

第二个流发出第一个事件后,它看起来像这样:

--a---b-c-d->
    (?)
-----1------>
    (=)
------b-c-d->

在第二个流中发生新事件后:

--a---b-c-d---e--f->
        (?)
-----1-------2----->
        (=)
--------------e--f->

依此类推......需要哪组操作员才能做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用CombineLatest按照自己的意愿返回事件,例如:

/* Have staggering intervals */
var source1 = Rx.Observable.interval(1000)
    .map(function(i) {

        return {
            data: (i + 1),

            time: new Date()
        };
    });

var source2 = Rx.Observable.interval(3000).startWith(-1)
    .map(function(i) {

        return {
            data: (i + 1),
            time: new Date()
        };
    });

// Combine latest of source1 and source2 whenever either gives a value with a selector
var source = Rx.Observable.combineLatest(
    source1,
    source2,
    function(s1, s2) {

        if (s1.time > s2.time) {
            return s1.data + ', ' + s2.data;
        }

        return undefined;
    }
).filter(x => x !== undefined).take(10);

var subscription = source.subscribe(
    function(x) {
        console.log('Next: %s', x);
    },
    function(err) {
        console.log('Error: %s', err);
    },
    function() {
        console.log('Completed');
    });

答案 1 :(得分:0)

我对你的弹珠不是百分之百,因为它们看起来有点矛盾,但如果你需要的是将所发生的事件分组在一起,我会建议使用windowbuffer的替代方案。在第二个来源的事件之后。

var count = 0;
//Converts the source into an Observable of Observable windows
source1.window(source2).subscribe(w => {
  var local = count++;
  //Just to show that this is indeed an Observable
  //Subscribe to the inner Observable
  w.subscribe(x => console.log(local + ': ' + x));
});

请注意,这只会从第一个来源发出值,如果您希望它们与其他来源的值相结合,那么请按照其他答案的建议使用combineLatestwithLatestFrom