I'm working on a project that uses Angular and by extension RxJS as well as the NGXS store management. I'm loading some values through selectors to a component and want to decide whether to use just a simple text field or an entire select based on a value in store.
In my component.ts file, I have the following construction:
` /* this variable decides whether to display simple text or the entire selection, if it is "locked", then the component will only display one value, if it is "unlocked", it will display the entire list of selection options */
lockSelectToText: boolean = false;
this.valueInStore$.pipe(
// filters out the initial null/undefined values
filter((value: string | undefined) => {
return !!value;
}),
// takes the first "defined" value in the stream, immediately unsubscribing afterwards
first(),
// disables the select if the value is 'foo'
tap(value => {
this.lockSelectToText = value === 'foo';
})).subscribe();`
Now, normally I wouldn't have bothered with the "first" operator here and simply stored the value in a subscription variable, unsubscribing from it in ngOnDestroy, but I wanted to experiment with RxJS a bit.
What I'm interested in is whether this actually does prevent memory leaks. If it ever happens that the valueInStore$ never gets set (say because for example the server doesn't ever return any response, leaving the value undefined), then the "first()" operator really doesn't do much and this subscription will be left hanging on the component indefinitely, right? What is the best practice here?