Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use switchMap to cancel pending http requests and taking the last subscribe only?

i tried canceling pending http request using subscription.unsubsribe like this:

getAgentList(pageNumber: number, filter: string): any {
   let requestUrl: string = 'api/service/agents_search?ACCT=' 
   +this.accountId;

if ( this.subscription ) {
    this.subscription.unsubscribe();
}

this.subscription =  this.backEndCommService.getData(requestUrl)
.subscribe(
        (res: any) => {
        let serverResponse: ServerResponse = new 
        ServerResponse(this.accountId, pageNumber, res.search_results, 
        res.resultRows, res.pageSize, res.resultPages)
                this._agentListData.next(serverResponse);
            },   
       (err: HttpErrorResponse) => {
                let errorMessage: string;
                if (err instanceof TypeError) {
                    errorMessage = 'Script error: ' + err.message;
                } 
                console.log(errorMessage);
    });
}

I wonder how can I apply switchMap to this code in order to kill pending requests to the URL ( for example autocompletion search input when first search taking to much time and a second one entered and I want to dismiss the first one.) thanks

like image 387
Shaul Naim Avatar asked Jan 02 '23 16:01

Shaul Naim


1 Answers

basic example:

export class MyComponent{
    private $filter: Subject<string> = new Subject<String>();

    constructor(){
        this.$filter
          .switchMap(filter => this.backEndCommService.getData(filter + this.baseUrl)
          .subscribe(res => {//do something})
    }

    getAgentList(filterValue: string){
        this.$filter.next(filterValue);
    }

}

To use switchmap to cancel previous request we need a hot observable which outputs our filter value. We use a subject for that. Everytime we get a new value from somewhere? we push it to the subject.

like image 189
Robin Dijkhof Avatar answered Jan 05 '23 15:01

Robin Dijkhof