我正在创建下面的类以促进单向数据流。有没有办法让outputError
方法不能使观察不可操作?我尝试添加subject.retry()
,如下所示,但它会导致无限循环。是否可以输出错误然后执行某些操作以防止subject.retry()
每次尝试重新连接时都会收到错误?
以下是我创建的课程的一部分:
/**
* Output data to be received by observe command of the same name
* @param name The name that will be listened for by observe
* @param data An object passed to observables success handler
*/
prototype.output = function (name, data) {
this._getReference('output', name).observer.onNext(data);
};
/**
* Listen for an output with the given name
* @param name The output name which is listened for
* @returns An observable instance
*/
prototype.observe = function (name) {
if (arguments.length > 1) throw new Error('Radio Channel: The observe method takes only one argument.');
return this._getReference('output', name).observable;
};
/**
* Output an error to be received by observe command
* @param name The name that will be listed for by observe
* @param error An error object passed to observables error handler
*/
prototype.outputError = function(name, error) {
this._getReference('output', name).observer.onError(error);
};
//Returns existing subject or creates a new one if it does not exist
prototype._getReference = function(type, name) {
name = this._createName(name);
var lookup = this['_' + type];
var result = lookup[name];
if (!result){
var subject = new rx.ReplaySubject(1);
lookup[name] = {
observable: subject, //.retry() results in infinite loop
observer: subject
} ;
result = lookup[name];
}
return result;
};
//Creates a consistent, non-integer key name
prototype._createName = function (name) {
return '$' + name;
};
您可以这样使用它:
channel.observe('refresh').subscribe(onLoaded, onError);
在不调用subject.retry()
的情况下,会调用onError函数,但是永远不会再调用onLoaded。我意识到我可以将error: true
的错误对象输出到onLoaded函数,但我更愿意封装更改而不是更改类的接口,以及有两个单独的函数来处理成功和错误。 / p>
答案 0 :(得分:0)
retry运算符重新订阅主题,希望这次不会收到onError事件。但是,当您显式调用onError(错误)时,同样的事情必须再次发生 - 毕竟您正在使用ReplaySubject,从而只重放前一个序列。
重试意味着与每次运行时可以具有不同输出的可观察对象一起使用。 jsbin
var counter = 0;
var respond = 4
var observable = Rx.Observable
.create(observable => {
if(counter == respond) {
observable.onNext('response');
observable.onCompleted();
} else {
observable.onError('error');
counter++;
}
})
.retry(respond + 1);
observable.subscribe(value => console.log(value),
error => console.log(error));
请注意,重试重试n-1次(重试(1)根本不重试)。如果要降低重试次数,则observable将失败。它现在的方式是返回'响应'成功完成。
是否可以将observable发送到您的ReplaySubject并只是concatMap主题以获取值?