0

i want to create an observable which handle these:

  1. observable
    • http request
    • Response
    • wait 5 sec and do the request again.

My current function:

  getData (): Observable<CurrentData> {
    return interval(5000)
      .pipe(
        flatMap(() => "HTTP REQUEST",
        ),
        map(this.extractData, this))
  }

but my function are not waiting for the successfull response, my function tries the request every 5 sec.

Saksham
  • 9,037
  • 7
  • 45
  • 73
KaOBWS
  • 3
  • 2

3 Answers3

2

user repeat and timer operator, or repeatWhen

  getData (): Observable<CurrentData> {
   return httpRequest().pipe(map(.....),timer(5000),repeat())
  }



  getData (): Observable<CurrentData> {
   return httpRequest().pipe(map(.....),repeatWhen(()=>timer(5000)))
  }
Fan Cheung
  • 10,745
  • 3
  • 17
  • 39
0

You can try the following. First create a BehaviorSubject and an Observable in your Service

private mySubject: BehaviorSubject<any> = new BehaviorSubject<>(null);
myObservable$: Observable<any> = this.mySubject.asObservable();

Then create the the function which will be triggerd once an then goes in an infinite loop.

loop() {
  var that = this;
  this.http.get(myUrl, { headers }).subscribe(
    (data: any) => { 
       this.mySubject.next(data);
       setTimeout(function () {
          that.timeout();
      }, 5000);
  } 
JuNe
  • 1,911
  • 9
  • 28
  • 1
    Why `setTimeout`? What about a pure `rxjs` way to do this so the code does not have to rely on `window.setTimeout`? – Igor Sep 26 '19 at 12:33
0

you can use exhaustMap operator , it will ignore until the last one complete

getData (): Observable<CurrentData> {
return interval(5000)
  .pipe(
    exhaustMap(() => "HTTP REQUEST",
    ),
    map(this.extractData, this))
}
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
  • Returns an Observable that emits items based on applying a function that you supply to each item emitted by the source Observable, where that function returns an (so-called "inner") Observable. When it projects a source value to an Observable, the output Observable begins emitting the items emitted by that projected Observable. However, exhaustMap ignores every new projected Observable if the previous projected Observable has not yet completed. Once that one completes, it will accept and flatten the next projected Observable and repeat this process. – KaOBWS Sep 26 '19 at 14:19