简体   繁体   中英

RXJS - IntervalObservable with .startWith

I have implemented http pooling in Angular app with IntervalObservable and startWith to start instantly. I wanted to know does IntervalObservable wait until initial/previous call finished streaming data? Is there a better way to implement data poolingin Angular app.

Ex from service.ts

getRecordsList() {
  return IntervalObservable
    .create(15000)
    .startWith(0)
    .flatMap((r) => this.http
    .post(`http://services.com/restful/recordService/getRecordsList`, body, {
      headers: new HttpHeaders().set('Content-Type', 'application/json')
    }))
    .shareReplay()
    .catch(this.handleError);
}

Ex from component.ts

ngOnInit() {
 this.service.getRecordsList()
  .subscribe(
    (recordList) =>  {
      this.recordResponse = recordList;          
    },
    error => { console.log },
    () => console.log("HTTP Observable getRecordsList() completed...")
);

}

I have used Angular httClient and I hope this doesn't matter anyhow.

Here's something that might help you:

const { Observable } = Rx;

// HTTP MOCK
const http = {
  post: () => Observable.of('some response').delay(1000)
}

// SERVICE PART
const polling$ = Observable.timer(0, 5000);

const myRequest$ = polling$
  .do(() => console.log(`launching a new request...`))
  .switchMap(() => http.post('some-url'));

// COMPONENT PART
myRequest$
  .do(res => console.log(`Response: ${res}`))
  .subscribe();

And a working Plunkr: https://plnkr.co/edit/BCTmlOv6FarNN1iUmMcA?p=preview

Your code seems reasonable to me. Here is a similar code that uses IntervalObservable to pool the server until some condition is met.

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { IntervalObservable } from 'rxjs/observable/IntervalObservable';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/operator/startWith';

@Component({
    selector: 'my-angular2-app',
    templateUrl: './tool-component.html',
    styleUrls: ['./tool-component.css']
})
export class ToolComponent {

    private _APIBaseURL = 'https://api.app.io';
    private _autoRefresh: boolean = true;
    private _downloadLink: string = ""
    private _fileID: string = ""

    constructor(private _http: Http) { }
    // add code here
    // ...

    getDownloadLink() {
        this._autoRefresh = true;
        this._downloadLink = "";
        IntervalObservable
            .create(10000)
            .startWith(0)
            .takeWhile(() => this._autoRefresh)
            .subscribe(() => {
                this._http.get(`${this._APIBaseURL}/rocess?file-name=${this._fileID}`)
                    .subscribe(data => {
                        let idata = data.json();
                        if (idata['current_status'] == "done") {
                            this._downloadLink = idata.url;
                            this._autoRefresh = false;
                        }
                    })
            }
            )
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM