我想知道是否有更优雅的方法来处理这段代码
return new Observable(subscriber => {
let subscription = this.anotherObservable().subscribe(
(next) => {
if (this.condition1(next)) {
subscriber.next(next);
} else if (this.condition2(next)) {
subscriber.complete();
} else {
subscriber.error('there was an error');
}
},
(error) => subscriber.error(error),
() => subscriber.complete()
);
return () => subscription.unsubscribe();
});
此代码位于类的方法内。
anotherObservable
返回一个发出不同类型数据的 Observable,这就是为什么 condition1
和 condition2
是基于 next< 的 bool 值
值。
我的问题是,我是否缺少一些可以以相同行为处理此 Observable 的运算符组合,但使用管道而不是重写“自定义”Observable?
最佳答案
结合使用 takeWhile 和 flatMap:
const subscription = anotherObservable.pipe(
takeWhile(someValue => !this.condition2(someValue)),
flatMap(someValue => {
if(this.condition1(someValue)) {
return of(someValue);
}
return throwError('there was an error');
})
).subscribe(someValue => //do something with value);
关于angular - 用管道控制 Observables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50644859/