I have a simple component which selects something from the state and listenes for the change:
private items$: Observable<Item[]>;
private alive: boolean = true;
contructor(private store: Store<state>) {
this.items$ = this.store.select(selectItems);
}
ngOnInit() {
this.items$
.pipe(
takeWhile(() => this.alive)
)
.subscribe((items: Item[]) => {
console.log('items changed!', items);
// dispatch some actions
});
}
ngOnDestroy() {
this.alive = false;
}
It works perfectly - each time the items change, I see the "items changed!" string logged. When I redirect somewhere else and the component is destroyed, the subscription doesn't run.
But when I redirect back to the component and subscription is active again, it immediately executes the same amount of changes as at the beginning, even though nothing changed.
For example, when I enter the page:
items changed! null
items changed! ['a', 'b', 'c']
items changed! ['a', 'b', 'c', 'd']
When I redirect and go back to the component:
items changed! ['a', 'b', 'c', 'd']
items changed! ['a', 'b', 'c', 'd']
items changed! ['a', 'b', 'c', 'd']
What's wrong here? I've tried takeUntil
and a subject, I tried unsubscribing manually - nothing solves the problem.