合并实现为flatMap

时间:2015-06-19 08:38:47

标签: javascript reactive-programming rxjs reactive-extensions-js

理论上应该可以通过just()实现任何RxJS运算符(flatMap()flatMap()除外)。例如,map()可以实现为

function map(source, selector) {
  return source.flatMap(x => Rx.Observable.just(selector(x)));
}

如何通过merge()实施flatMap()? (当然也避免mergeAll()

1 个答案:

答案 0 :(得分:4)

如果你利用flatMap也可以获取数组返回值的事实,那么看起来很可能。

Rx.Observable.prototype.merge = function(other) {
  var source = this;
  return Rx.Observable.just([source, other])
           //Flattens the array into observable of observables
           .flatMap(function(arr) { return arr; })
           //Flatten out the observables
           .flatMap(function(x) { return x; });
}

我真的希望它只是Erik拖钓:)。

var source1 = Rx.Observable.interval(2000).timestamp().map(function(x) {
  return "Interval 1 at " + x.timestamp + " w/ " + x.value;
});
var source2 = Rx.Observable.interval(3000).timestamp().map(function(x) {
  return "Interval 2 at " + x.timestamp + " w/ " + x.value;
});

Rx.Observable.prototype.mergeFromFlatMap = function(other) {
  var source = this;

  return Rx.Observable.just([source, other])
    .flatMap(function(arr) {
      return arr;
    })
    .flatMap(function(seq) {
      return seq;
    });

};


source1.mergeFromFlatMap(source2).take(20).subscribe(console.log.bind(console));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.3/rx.all.js"></script>