Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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;
            });
    }
}
question from:https://stackoverflow.com/questions/36612945/how-to-get-an-observable-to-return-data-immediately-and-every-5-seconds-thereaft

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Got it:

        .interval(5000)
        .startWith(0);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...