我正在寻找一种方法,每当有人在实现Observable
的给定类的实例上调用subscribe
时,就执行回调.
在RxJS库中没有钩子的情况下,在几乎任何其他面向对象语言中,我会:
- 继承我想要定制的类(本例中为
ReplaySubject
); - 覆盖
subscribe
方法;以及 - 执行我的回调,然后将调用委托给超类‘
subscribe
方法.
大概是这样的:
export class CallbackReplaySubject<T> extends ReplaySubject<T> {
subscribe(observer: Partial<Observer<T>>): Unsubscribable {
this.triggerCallback();
return super.subscribe(observer);
}
private triggerCallback(): void {
// do something when someone subscribes
}
}
在使用TypeScrip的RxJS v7中,我收到以下错误消息:
Property 'subscribe' in type 'CallbackReplaySubject<T>' is not assignable to the same property in base type 'ReplaySubject<T>'.
Type '(observer: Partial<Observer<T>>) => Unsubscribable' is not assignable to type '{ (observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | undefined): Subscription; (next?: ((value: T) => void) | null | undefined, error?: ((error: any) => void) | ... 1 more ... | undefined, complete?: (() => void) | ... 1 more ... | undefined): Subscription; }'.
Type 'Unsubscribable' is missing the following properties from type 'Subscription': closed, _parentage, _finalizers, add, and 4 more.
我越深入地研究这一点,就越会接触到被标记为内部的"带下划线的"RxJS方法,它们喊着"请勿使用!"在我身上,阻止任何定制.
因此,我try 了委托模式,而不是继承.这也行不通,因为Observable
不是一个接口,而是一个类.因此,我又一次被这些"带下划线"的内部方法和成员缠住了.
有谁能告诉我一条出路吗?
直到包括RxJSV6,我都能够通过继承来解决这个问题,继承了ReplaySubject
‘S内部的_subscribe
方法.