I'm exploring methods to delay an HTTP request until the user stops interacting. I am considering using the debounceTime()
operator from RxJs, but I need this to be triggered by changes in an array that I have defined.
Here is the scenario:
export class KeywordSelectionComponent implements OnInit {
constructor(private proposalService: ProposalService) { }
@ViewChild(MatTable, {static: true}) kwTable: MatTable<any>;
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
@Input() proposalId: string;
keywordInput = new FormControl(null, Validators.required);
dataSource: MatTableDataSource<Keyword>;
displayedColumns = ['action', 'keyword', 'searches', 'competition', 'cpc'];
suggestedKeywords: Keyword[] = [];
selectedKeywords: string[] = [];
fetchSuggestions(seeds?: string[]) {
const ideas = {
seeds: [],
limit: 25
};
this.proposalService.getKeywordIdeas(this.proposalId, ideas).pipe(retry(3)).subscribe(res => {
this.suggestedKeywords = res;
});
}
}
I'm not showing the complete component code here, but essentially:
I display a list of suggestedKeywords
on the page, each triggering the addKeyword()
method when clicked to add it to the dataSource
. After clicking, the fetchSuggestions()
method is called to update the suggestedKeywords
list with new keywords.
The issue arises when multiple keywords are quickly selected, causing a request for each click to update the suggestedKeywords
list. To prevent this and wait for a pause in interactions before making the request, I wanted to use debounceTime()
. However, since my data source is just a simple array, I'm unsure how to make it trigger like an Observable.
Is there a way to mimic Observable behavior with array values so that an HTTP request is delayed after changes occur, similar to using Observables?
EDIT: Following suggestions in the comments, I used the from()
operator. Should I define additional methods to listen for changes? Something akin to valueChanges()
in FormControls
.
After further reading, I'm considering using Subject
, BehaviorSubject
, etc.; however, I'm uncertain if this is the correct approach. Could someone provide an example of how to implement this?