从Rx.Observable.prototype外部访问源可观察对象

时间:2017-01-09 09:29:38

标签: javascript node.js rxjs5 angular2-observables

我无法弄清楚如何访问源observable,在这个方案中(只是试图弄清楚如何在不修改Rx.Observable.prototype的情况下):

      q.drain()
        .flatMap(function(val){
            return q.backpressure(val, function(cb){
                   setTimeout(cb,1000);
            });
        })

我们将backpressure称为Queue原型的一种方法:

Queue.prototype.backpressure = function(val, fn){

    const source = ? // I don't know how to access the source observable...

    return Rx.Observable.create(sub => {

        return source.subscribe(val => {

                fn.call(source, val, function(err, val){
                    if(err){
                        sub.error(err);
                    }
                    else{
                        sub.next(val);
                    }

                });
            },
            // be sure to handle errors and completions as appropriate and
            // send them along
            err => sub.error(err),
            () => sub.complete());

    });
};

但问题是我不知道我是否可以访问此方案中的源observable - 源的正确值肯定原型内的this值因为属于队列实例。我认为我唯一的希望是以某种方式直接将源观察源传递给背压方法。谁知道我怎么能这样?我不介意把这个函数放在别处,它不一定是队列中的方法,但我认为同样的问题将存在。

如果有帮助,flatMap函数中的this值(如果使用常规函数而不是箭头函数)是MergeMapSubcriber对象,请参阅:

enter image description here

然而,经过实验,我不相信MergeMapSubcriber值是我想用作源的那个;我的来源应该是一个Observable TMK,而不是订阅者。

1 个答案:

答案 0 :(得分:1)

您是否考虑将其放在Observable原型上?

Observable.prototype.backpressure = function(queue, fn){
  const source = this;

  return this.flatMap(function(val){
    return Rx.Observable.create(sub => {

      return source.subscribe...
    });
  })
};

然后是队列:

q.drain()
  .backpressure(q, function(cb) {
    setTimeout(cb,1000);
  });
相关问题