我需要通过一个主题代理所有不同的事件流。
我想出了这段代码:
var mySubject,
getObservable;
getObservable = function (subject, eventName) {
return subject
.asObservable()
.filter(function (x) {
return x.EventName === eventName;
})
.flatMap(function (x) {
if (x.Type === 'onNext') {
return Rx.Observable.return(x.Data);
}
if (x.Type === 'onError') {
return Rx.Observable.throw(x.Data);
}
return Rx.Observable.empty();
});
};
mySubject = new Rx.Subject();
getObservable(mySubject, 'foo')
.subscribe(function(x){
console.log('foo onNext ' + x);
}, function(x){
console.log('foo onError ' + x);
}, function(){
console.log('foo onComplete');
});
getObservable(mySubject, 'bar')
.subscribe(function(x){
console.log('bar onNext ' + x);
}, function(x){
console.log('bar onError ' + x);
}, function(){
console.log('bar onComplete');
});
mySubject.onNext({Type: 'onNext', EventName: 'foo', Data: 5});
mySubject.onNext({Type: 'onCompleted', EventName: 'foo'});
mySubject.onNext({Type: 'onNext', EventName: 'bar', Data: 5});
mySubject.onNext({Type: 'onError', EventName: 'bar', Data: 'Error message'});
得到输出:
foo onNext 5
bar onNext 5
bar onError Error message
预期输出:
foo onNext 5
foo onCompleted
bar onNext 5
bar onError Error message
对于bar
事件,它就像一个魅力:onNext
将被传播,一旦错误引发,onError
函数就会被调用并且事件流结束。但是,我无法让它为onComplete
.
每当发出完整的通知时,我确实会看到它Rx.Observable.empty()
被调用,但这不会导致订阅者onComplete
处理程序被调用。相反,它调用它的onNext
处理程序。