Header
If you are essentially having the same question and your context is Angular you may want to read all the comments in the answer for more context.
Short version of this question
When doing let observe$ = someReplaySubject.asObservable()
, are we no longer required to unsubscribe from observe$
? In other words can we call let observe$ = someReplaySubject.asObservable()
from multiple Angular component instances and not worry about the connection from the notify
instance to the corresponding Observable
?
Assumptions
If we have a ReplaySubject<Todo[]>
instance (Lets call it rxTodo
and we subscribe to it from Angular components by doing:
let todoObs$:Observable<Todo[]> = rxTodo$.asObservable()
then even if the component is destroyed the todoObs$
references created in each component will dangle until the component itself is destroyed.
Background
I'm attempting a Store
API for Angular and I have a replay subject that broadcasts changes to slices of the store. Here is the method that allows subscriptions to happen (The notifyCount tracks subscriptions, so that if there are none we don't bother with notification):
/**
* Subscribe to receive slice updates.
* @example
<pre>
let todos$ = slice.subscribe();
</pre>
*/
public subscribe(): Observable<E[]> {
this.notifyCount++;
return this.notify.asObservable();
}
Above I'm attempting to follow the recommended best practice of returning an Observable
instead of from the ReplaySubject
.
This is the corresponding unsubscribe
method:
/**
* Unsubscribe from slice updates.
*
* @example
<pre>
slice.unsubscribe(o);
</pre>
*/
public unsubscribe(o: ReplaySubject<E[]>) {
o.unsubscribe();
this.notifyCount--;
}
I had to make the o
argument a ReplaySubject
type in order to unsubscribe
. However that conflicts with the Observable
type that the subscribe
method returns.
When attempting to test like this:
incompleteSlice.unsubscribe(incomplete$);
The message returned is this:
[ts] Argument of type 'Observable' is not assignable to parameter of type 'ReplaySubject'. Property 'scheduler' is missing in type 'Observable'. let incomplete$: Observable
Any thoughts on how to fix this?
Update
One obvious thought that just came to mind is that perhaps returning asObservable
means that we no longer need to actually unsubscribe
from that observable. We can just leave it dangling in the event that the Angular component is destroyed?