How to only execute an Observable if term is not null/empty?
If you want to avoid the API call and want the search results to be reset when the search term is empty, test for an empty string in switchMap
and return an empty observable in that situation:
this.searchResults = this.searchTerm
.valueChanges
.debounceTime(500)
.distinctUntilChanged()
.switchMap(term => term ?
this.apiService.search({
limit: this.searchResultsLimit,
term: term
}) :
// If search term is empty, return an empty array
// or whatever the API's response for no matches
// would be:
Observable.of([])
});
In Rxjs 6 so updated to use pipe
you can stop the observable from processing so nothing is propagated downstream using EMPTY
:
this.searchResults = this.searchTerm.valueChanges
.pipe(
debounceTime(500)
distinctUntilChanged()
switchMap(term =>
(term)
// If the term exists make a request
? this.apiService.search({ limit: this.searchResultsLimit, term: term })
// Otherwise, stop all processing
: EMPTY
)
)
);
Most easily just use the filter()
operator to filter out all empty term
s:
this.searchResults = this.searchTerm.valueChanges
.filter(term => term) // or even better with `filter(Boolean)`
.debounceTime(500)
.distinctUntilChanged()
.switchMap(term => this.apiService.search({
limit: this.searchResultsLimit,
term: term
}));