RxJs Observable Zip Array of Observables

2019-04-12 04:40发布

问题:

There is an example of using zip to combine a fixed number of observables like the following:

var range = Rx.Observable.range(0, 5);
var source = Observable.zip(
      range,
      range.skip(1),
      range.skip(2),
      function (s1, s2, s3) {
            return s1 + ':' + s2 + ':' + s3;
      }
)

My questions is what if I have an array of observables (length can be anything), how to accomplish the same like zip?

var arr = [observable1, observable2, ..]; //like 100 of them!
var source = Observable.zip(
      //how to put each observable here?
      function (__how to put argument here?_) {
            return /* loop through arguments*/;
      }
)

回答1:

In theory, you can use a combination of .apply() and the arguments variable to accomplish this. Full disclosure: I have not tried this code.

var arr = [observable1, observable2, ..]; //like 100 of them!
var source = Observable.zip.apply(Observable, 
     arr.concat(function (varargs) { // using "varargs" purely for documentation
         Array.prototype.forEach.apply(arguments, function (observableValue) { 
            /* do something with observableValue */;
         });
     })
);