I'm not really sure if I'm doing this correctly.
I have a simple function that has an argument which I want to use inside a combineLatest observable. That observable is then returned.
fn(arg) {
return combineLatest([
observable...,
observable...,
]).pipe(
map(() => arg)
);
}
The issue here is that when the function is called many times, it creates duplicate observables.
What would be the proper solution? To make the argument an observable too? So the function is only called once but it returns the correct value when the argument changes.
Solution is not use Observables this way. Use a Subject for that kind of things:
readonly actionSubject = new Subject<unknown>();
...
ngOnInit(): void {
this.actionSubject.pipe(
switchMap(newValue =>
combineLatest([
observable...,
observable...,
]).pipe(map(() => newValue)),
)
).subscribe();
}
...
ngOnDestroy(): void {
this.actionSubject.complete();
}
And in place of your function usage instead of fn:
this.actionSubject.next(someNewValue);
What happens here? SwitchMap will stop you old thread and start new one every time you have new value. That's solution.