There must be a simple answer to this, but my GoogleFoo fails me. I have a service that registers events from all over my application, and create ReplaySubjects for them (simplified to just Subjects in the code below).
However, sometimes someone wants to register with their own Subject (mostly from legacy code). If no one has subscribed to the original Subject I made them, no problem, we just replace it, but what if someone subscribed to the original? I now want to transfer these over to the newly brought Subject, and then replace the old with the new;
events.ts
registry:any = {};
register ( key:string, incomingSubject:Subject = null ) {
let s = incomingSubject ? incomingSubject : new Subject();
if ( !this.registry[key] ) {
this.registry[key] = s;
}
}
when ( key:string ) {
if ( this.registry[key] ) {
return this.registry[key];
}
if ( this.registry[key] ) {
return this.registry[key];
}
}
some-quick-component.ts
events.when('bigEvent').subscribe( console.log );
some-slower-service.ts
events.register('bigEvent', myOwnSubject);
When the slower some-slower-service.ts comes along and registers, I essentially want all subscribers to the one I created initially to be transferred to the new one, and then kill the old and put the new in its place (so new subscriptions goes to the new one), something like (see the 'existing Subject' comment section for pseudo code);
register ( key:string, incomingSubject:Subject = null ) {
let s = incomingSubject ? incomingSubject : new Subject();
if ( !this.registry[key] ) {
this.registry[key] = s;
} else {
if ( incomingSubject ) {
// ----------------------------------------
// existing Subject, *and* incoming Subject
// ----------------------------------------
let tmp = mergeTwoSubjects(this.registry[key],s);
this.registry[key].unsubscribe();
this.registry[key] = tmp;
}
}
}
Everything I search up seems to combine or merge Subject streams, creating new Observables in the process but still needing the old to exist and listen to streams, however here I want to replace one Subject with another, but making sure I move all subscriptions from the old to the new before I unsubscribe() the old Subject.
Or, have I got all of this back to front?