I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject
private subjects = {
a : new BehaviorSubject<A>(this.a),
b : new BehaviorSubject<B>(this.b),
c : new BehaviorSubject<C>(this.c),
d : new BehaviorSubject<D>(this.d),
e : new BehaviorSubject<E>(this.e),
}
In order to prevent exposing the Observer
side of these subjects and only make the Observable
side accessible, I have kept the subjects private and exposed them as observables:
observables = {
a : this.subjects.a.pipe(share()),
b : this.subjects.b.pipe(share()),
c : this.subjects.c.pipe(share()),
d : this.subjects.d.pipe(share()),
e : this.subjects.e.pipe(share()),
}
I believe that the process of generating observables from the subjects should be automated so that when additional subjects are added, manual adjustments to the observables are not required. This could be done in a way similar to the following:
observables = (()=>{
let observables : {[Property in keyof typeof this.subjects]:Observable} = {}
for(let key in this.subjects)
{
observables[key] = this.subjects[key as keyof typeof this.subjects].pipe(share())
}
return observables;
})();
The challenge here lies in defining the generic type for Observable
and share
. How can I overcome this issue or is there a better design pattern available?