我正在实现一个角度服务,让消费者根据他们的 id 观察各种值:
它的本质是这样的:
private subjects = new Map<number, Subject<any>>();
public subscribe(id: number, observer: any): Subscription {
// try getting subject for this id (or undefined if it does not yet exist)
let subj = this.subjects.get(id);
// create subject if it does not yet exist
if (!subj) {
subj = new Subject<any>();
this.subjects.set(id, subj);
}
// subscribe observer
const subscription = subj.subscribe(observer);
// set up teardown logic (gets called when subscription is unsubscribed)
subscription.add(() => {
// remove subject from the map, if this was the last subscription
if (subj.observers.length == 0) {
this.subjects.delete(id);
}
});
// return subscription
return subscription;
}
以上工作正常,但 API 使用起来有点麻烦(在消费者中,我需要手动跟踪所有订阅并确保正确取消订阅)。
我希望有一个返回Observable
这样的方法:
public subscribe(id: number): Observable<any> {
// TODO: Return an observable for this id and make sure that
// its corresponding subject is in the map iff at least one of the observables
// for this id has at least one subscription.
return ...;
}
因为这将允许我使用管道直接从组件模板订阅我需要的值async
,其中 angular 将负责取消订阅观察者。
但是我不太清楚如何实现逻辑以从不再使用它们时删除未使用Subject
的 s 。Map
有什么好的方法吗?