There are different patterns for tearing down subscriptions in angular components. I've been using the Subject
/ takeUntil
pattern, in this form:
export class FooComponent implements OnDestroy {
private destroy$ = new Subject<void>();
...
source$.pipe(takeUntil(this.destroy$)).subscribe(...);
...
ngOnDestroy() {
this.destroy$.next();
}
}
Today I've been told to add another line to the ngOnDestroy
:
this.destroy$.complete();
After doing a bit of research, it does show up on some online examples and not in others, but either way I'm failing to see the point. Looking at the source code of Subject.complete it will loop through any inner observers and complete these. Assuming we don't subscribe to the destroy$
subject directly, isn't this list of inner observers always supposed to remain empty? If that's the case isn't that call to this.destroy$.complete()
redundant?
You don't need to call complete()
if you're using destroy$
only for takeUntil()
operators.
When destroy$
emits next
takeUntil()
will complete the chain that will also unsubscribe from destroy$
and thus there will be no subscribers so complete()
should not be necessary.
Btw, I've seen people using complete()
in this situation as well. I can't find any example right now but in contrast ngrx/component-store
is just calling next()
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments