I have a selector and I subscribe to them on ngOnInit; but the code inside the subscribe is executed every time when the page is initialized (refreshed).
@Select(SurveysSelectors.deleteSurveys) deleteSurveys$: Observable<IDeleteSurveys>;
.
.
.
ngOnInit(): void {
this.deleteSurveys$.pipe(takeUntil(this.destroy$), debounceTime(600)).subscribe((result: IDeleteSurveys) => {
if (!result.surveyDeleteResult.esriUpdate) {
return;
}
this.esriUpdate(result.surveyIds, result.surveyDeleteResult.iotFunc);
});
}
Is this normal? I expected that the code inside subscribe to run only when a change is made on the slice of state that selector returns.
this is expected since your ngOnInit
will run every time your component is initialized. In NGXS the selectors are hot and always will emit on subscription the last value, in this case the initial value. A possible workaround would be to use a skip(1)
to be sure you only react to changes that happen after you subscribed.
Example below:
this.deleteSurveys$.pipe(takeUntil(this.destroy$), skip(1), debounceTime(600)).subscribe((result: IDeleteSurveys) => {
if (!result.surveyDeleteResult.esriUpdate) {
return;
}
this.esriUpdate(result.surveyIds, result.surveyDeleteResult.iotFunc);
});
I hope this can help you.