rxjs is pretty challenging for me and I have found myself stuck trying to solve this problem. The closest solution I have found on stack is the usage of merge operator. Here is the link
I am working in angular 2.
I have an input search field in html
<input (keydown.enter)="setFocus()" id="search-box" name="input-box" class="search-box" type="text" placeholder="Client search" (focus)="clearWarnings()" />
The user types in the field box which will trigger the corresponding function after a preset delay. Also the user may press the enter key( and a search icon) to trigger the search. What I aim here is to whenever the user hits the enter key, the debounce should NOT trigger the search because it is already running.
Here is the code so far using the merge function although it does not seem to work the way I intend.
ngAfterViewInit() {
this.currentMember = this.appHelpersService.getLocalStorageSearchedRim();
if (this.currentMember) {
this.searchService.changeSearchTerm(this.currentMember);
}
var waitTime = AppConstants.SEARCH_TEXT_WAITTIME;
const searchSource = document.getElementById("search-box");
const keydownStream = fromEvent(this.elementRef.nativeElement, 'keyup');
const inputStream = fromEvent(searchSource, "input");
const allStreams = merge(keydownStream, inputStream);
allStreams
.pipe(
map((event: KeyboardEvent | MouseEvent) => (<HTMLInputElement>event.target).value.trim()),
filter((searchTerm: string) => {
waitTime = Number(searchTerm) ? AppConstants.SEARCH_NUMERIC_WAITTIME : AppConstants.SEARCH_TEXT_WAITTIME;
return searchTerm.length >= 2;
}),
debounce(() => timer(waitTime)),
distinctUntilChanged()
)
.subscribe((searchTerm: string) => {
this.showProgressbar = true;
this.listSearchResults(searchTerm);
});
}
And the enter key event:
setFocus(): void {
const searchBox: HTMLElement = document.getElementById("search-box");
const searchTerm = (<HTMLInputElement>searchBox).value;
if (searchTerm && searchTerm.length > 0) {
this.listSearchResults(searchTerm);
}
searchBox.focus();
}
In the solution I have mentioned all events merged together will trigger the function but not necessarily cancel the other event that is waiting (debounce).
Thanks for the time