Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an observable to return data immediately and every 5 seconds thereafter

Tags:

rxjs

rxjs5

I want to create an observable that returns data from a webapi. I'd like it to return the data immediately, and poll the API every 10 seconds. The code below shows I'm using the 'interval' method. But this delays the first set of data by 10 seconds. How do I get that first flush of data to come down with no initial delay?

export class EventService {
    public events$: Observable<Event[]>;
    private _eventsObserver: Observer<Event[]>;
    private pollInterval: number = 5000;

    private _dataStore: {
        events: Event[];
    };

    constructor(private http: Http) {
        this._dataStore = { events: [] };

        this.events$ = new Observable(observer => this._eventsObserver = observer)
            .startWith(this._dataStore.events)
            .share();
    }

    pollEvents() {
        return Observable.interval(10000)
            .switchMap(() => {
                return this.http.get('app/resources/data/scheduleevents.json')
                    .map((responseData) => {
                        return responseData.json();
                    });
            })
            .map((events: Array<any>) => {
                let result: Array<Event> = [];
                if (events["data"]) {
                    events["data"].forEach((event) => {
                        result.push(event);
                    });
                }
                return result;
            });
    }
}
like image 612
FeeFiFoFum Avatar asked Apr 14 '16 02:04

FeeFiFoFum


People also ask

What is Observable interval?

interval returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between those emissions. The first emission is not sent immediately, but only after the first period has passed.

Is Observable lazy?

No, they aren't lazy, but they are asynchronous.

Does Observable have next?

Executing Observableslink There are three types of values an Observable Execution can deliver: "Next" notification: sends a value such as a Number, a String, an Object, etc. "Error" notification: sends a JavaScript Error or exception. "Complete" notification: does not send a value.

What does Observable subscribe return?

Subscriptions to observables are quite similar to calling a function. But where observables are different is in their ability to return multiple values called streams (a stream is a sequence of data over time). Observables not only able to return a value synchronously, but also asynchronously.


Video Answer


3 Answers

Got it:

        .interval(5000)
        .startWith(0);
like image 53
FeeFiFoFum Avatar answered Oct 19 '22 14:10

FeeFiFoFum


Use timer. I think the timer is what you need (see RxJS tab): http://reactivex.io/documentation/operators/timer.html#collapseRxJS

Could be used like:

Observable.timer(0, 5000).flatMap(() => apiCall())

Where 0 - delay before emitting the first value, 5000 - emit value after each 5s

enter image description here

like image 45
Maksim Nesterenko Avatar answered Oct 19 '22 14:10

Maksim Nesterenko


    let timer = TimerObservable.create(0, 5000);
    this.sub = timer.subscribe(t => {
        this.yourMethod()
    });

To unsubscribe run this.sub.unsubscribe()

like image 3
Yossi Neiman Avatar answered Oct 19 '22 13:10

Yossi Neiman