I have a component as follows, where I have a button calling select_property when clicked. The thing is im not sure whether i need to unsubscribe in any way before reassigning $livevisitors on each click , not sure whether $livevisitors | async in the component template does this work for me.
export class LiveComponent{
livevisitors$: Observable<LiveVisitor[]>;
selected_property_id: number = 0;
constructor(
private store: Store<AppState>
) {
this.livevisitors$ = this.store.select(selectAllLiveVisitors);
}
select_property(id){
this.selected_property_id = id;
if (id == 0){
this.livevisitors$ = this.store.select(selectAllLiveVisitors);
} else {
this.livevisitors$ = this.store.select(selectLiveVisitorsByPropertyId, {property_id: id});
}
}
The async pipe subscribe and unsubscribe for you. You don't need to manage manual unsubscription.
From the official documentation :
When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
However if you subscribe to the observable in your component, you introduce a potential memory leak:
export class LiveComponent{
livevisitors$: Observable<LiveVisitor[]>;
selected_property_id: number = 0;
constructor(
private store: Store<AppState>
) {
}
ngOnInit() {
//Potential memory leak
this.store.select(selectAllLiveVisitors).subscribe(() = > {...})
}
}
if that is the case then you need to unsubscribe when the component is destroyed. An elegant solution to this is to declare a Subject property:
export class LiveComponent implements OnInit, OnDestroy {
destroyed$: Subject<void> = new Subject<void>();
livevisitors$: Observable<LiveVisitor[]>;
selected_property_id: number = 0;
constructor(
private store: Store<AppState>
) {
}
ngOnInit() {
// will unsubscribe when component is destroyed
this.store.select(selectAllLiveVisitors)
.pipe(takeUntil(this.destroyed$))
.subscribe(() = > {...})
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With