Within my Angular 2
application written in typescript 2
, a server query is made to retrieve a value that requires regular updates based on an expiration date provided by the server.
I am facing difficulties in creating an Observable stream that will automatically trigger a new call to the server once the current value has expired. The approach I have taken so far is not efficient at all:
price = 5; //initial known value
expires = ...;//initial known expiration
getData(){
// server response contains {expires:number, price:number}
this.http.get('...').map(res => res.json())
}
Observable.timer(expires-Date.now()) // when initial price expires
.switchMap(()=>this.getData()) // fetch new price and expiration
.subscribe( data =>
{
this.price = data.price;
Observable.timer(data.expires-Date.now()) //redo when price expires
.switchMap(()=>getData())
.subscribe(...) //nested callbacks (endless blocks)
}
);
There must be a more efficient way to schedule subsequent calls after the initial query.