3

I have a service that get data from a server every 3 seconds. Sometimes the server is very slow and many responses comes after 5 or 6 seconds. When this happen ,my service starts to cancel each request instead of waiting the pending one. How can I prevent this?

public getCallDiagnostic():Observable<IRespWidgets>{

        let body = JSON.stringify({manager:"CallDiagnosticServiceManager",
                                   action:"GetCallDiagnostic",
                                   WEB_USER_TOKEN:this._authenticationService.getUserToken()});     
        let options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

        return  Observable.timer(0,3000)
                .switchMap(()=>this._http.post(this._apiUrl,body,options))                      
                .map(res => <IRespWidgets>res.json().data)          
                .catch(this.handleError);       
    }
Massimo Magliani
  • 649
  • 2
  • 7
  • 17

1 Answers1

9

Your requests are getting cancelled since you are using switchMap. If you want to receive the response from every request, just use mergeMap:

return  Observable.timer(0,3000)
            .mergeMap(()=>this._http.post(this._apiUrl,body,options))                      
            .map(res => <IRespWidgets>res.json().data)          
            .catch(this.handleError);       

This will never cancel a request and you'll get back the response from every request.

Edit: If you want to perform the next request as soon as the previous arrives you can use concatMap. ConcatMap will take the next value and process it. It will not take a next value (even if it arrives) as long as the previous one isn't handled.

return  Observable.timer(0,3000)
            .concatMap(()=>this._http.post(this._apiUrl,body,options))                      
            .map(res => <IRespWidgets>res.json().data)          
            .catch(this.handleError);    
KwintenP
  • 4,637
  • 2
  • 22
  • 30
  • thanks so much What is the better way to send a request only if the previous one is arrived? – Massimo Magliani Nov 11 '16 at 10:07
  • @KwintenP can i do this like i have done it here : http://plnkr.co/edit/6fBPFCus3HhZmCFBXFKq Ofcourse i am only referring to requirement where every request should wait for the previous one to complete – Shailesh Vaishampayan May 30 '17 at 09:58
  • I don't think using repeat will allow you to only start doing the next request when the previous has finished. – KwintenP May 31 '17 at 06:06
  • `concatMap` seems to be right thing here, thanks. Not a `switchMap` and definitely not a `mergeMap` – Alexander Nov 03 '22 at 23:30