Reputation:
I have the following code:
public clearSearch$ = new Subject<boolean>();
this.clearSearch$.pipe(mergeMap(() => this.searchResults$)).subscribe((groups: SearchGroup[]) =>
groups.forEach((group) => {
this.searchService.deleteResultGroup(group);
}),
);
I call subject only once using click method:
public clear() {
this.clearSearch$.next();
}
Problem is when a new data comes to this.searchResults$
the block this.clearSearch$.pipe(mergeMap(() => this.searchResults$)).subscribe()
works again. How to avoid it and call it only by click?
Upvotes: 0
Views: 28
Reputation: 71891
There are two ways (probably more, it's coding after all..).
Use a take(1)
like you said. This won't unsubscribe from the clearSearch$
just from the inner observable:
this.clearSearch$.pipe(
switchMap(() => this.searchResults$.pipe(take(1))
).subscribe((groups: SearchGroup[]) =>
groups.forEach((group) => {
this.searchService.deleteResultGroup(group);
}),
);
This won't work if you place the take(1)
on the outer observable:
// this will only be triggered once. Don't use this
this.clearSearch$.pipe(
switchMap(() => this.searchResults$),
take(1)
).subscribe((groups: SearchGroup[]) =>
groups.forEach((group) => {
this.searchService.deleteResultGroup(group);
}),
);
Or you can also use withLatestFrom
:
this.clearSearch$.pipe(
withLatestFrom(this.searchResults$)
).subscribe(([_, groups]) => {
groups.forEach((group) => {
this.searchService.deleteResultGroup(group);
}),
});
Upvotes: 1