Akkusativobjekt Akkusativobjekt - 1 month ago 18
TypeScript Question

Start first call of IntervalObservable instant

I'm using an

IntervalObservable
to make continuous calls to the server side of my application. I can subscribe and unsubscribe to to the Oberservable and everything works fine with one exception:

The first call to the server is delayed, but I want it to be instant. The behaviour of the
IntervalObservable
is in principle correct, but does not match my requirements.

@Injectable()
export class LoggerService {
constructor(private http: Http) { }
private apiURL = 'assets/file.json';

getList() {
return IntervalObservable.create(1000).flatMap(()
=> this.http.get(this.apiURL))
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
var fooot = new Foo();
fooot.fillFromJSON(JSON.stringify(res.json()));
return fooot;
}

private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return IntervalObservable.throw(errMsg);
}
}


So how can I call the server instant on the first call and afterwards with the defined delay?

Answer

You can use startWith.

Following example pushes an event on the stream when it is created:

 getList() {
    return IntervalObservable.create(1000)
     .startWith(1) // needs a value, but won't be used
     .flatMap(() => this.http.get(this.apiURL))
     .map(this.extractData)
     .catch(this.handleError);  
 }
Comments