4

I'm trying to create a service that polls a log at given interval (every 5 seconds). I need to make an http GET call, but on slow connections and large logs, the switchMap cancels the previous pending request. Thus, I'm never getting the log as the request is being canceled.

getLog(url:string):Observable<string> {
    return Observable
        .timer(0, 5000)
        .switchMap(() => this.get(url))
        .retryWhen(error => error.delay(5000))
        .map((res:Response) => res.text())
        .catch(e => {
            console.warn(e.toString());
            return Observable.from("");
        });
}

and this.get(url) is simply get(url) {return this.http.get(url)}.

I am seeking to keep the timer functionality, but to not trigger another http call until the previous call has resolved, and to not cancel the pending call.

bomba6
  • 539
  • 1
  • 7
  • 21
  • Possible duplicate of [What is the difference between flatmap and switchmap in RxJava?](http://stackoverflow.com/questions/28175702/what-is-the-difference-between-flatmap-and-switchmap-in-rxjava) – jonrsharpe Apr 09 '17 at 07:53
  • To put it another way: use `flatMap` instead. – jonrsharpe Apr 09 '17 at 07:57
  • @jonrsharpe `flatMap` keeps creating new requests. I don't want to create new requests until the pending request has finished. – bomba6 Apr 09 '17 at 08:11
  • 1
    Oh, I thought the requests being cancelled was the problem; please [edit] to clarify the behaviour you're looking for. – jonrsharpe Apr 09 '17 at 08:16

1 Answers1

6

Use concatMap() instead of switchMap().

As you said the switchMap() operator cancels the previous requests. The flatMap() (or mergeMap()) operator just creates another Observable and subscribes to all of them immediately.

On the other hand, the concatMap() operator waits until the previous Observable completes and then subscribes to the next Observable. So even if your timer is emitting faster than the requests are finished you'll always receive all their responses in the same order.

Graham
  • 7,431
  • 18
  • 59
  • 84
martin
  • 93,354
  • 25
  • 191
  • 226