POV
POV

Reputation: 12025

Correct way to use FlatMap in Rx?

Is it correct way to use flatMap?

const observer = Observable
    .interval(3000)
    .takeUntil(Observable.timer(10000))
    .flatMap(this.askToReadyRecordVideo);

private askToReadyRecordVideo(): Observable<any> {
    return this.requestMethods.askToReadyRecordVideo({});
}

In this line I tied to send request to server each 3 seconds until 10 seconds then call method this.askToReadyRecordVideo() that returns data from server.

I finish this when I get successfull response. Is it true?

Upvotes: 1

Views: 95

Answers (1)

Hero Wanders
Hero Wanders

Reputation: 3302

I'm not sure whether I understand you correctly, but your code does the following: The method askToReadyRecordVideo will get called every 3 seconds until 10 seconds are over (there will be three calls, at 3s, 6s and 9s). Your observable observer will emit the results of those server calls.

If you want to cancel the process after your first successful response add the following:

.filter(resp => /* return true when resp indicates success */)
.take(1)

If every answer is a success (i.e. errors are indicated by an error event pushed through the observable), then just omit the filter line.

By the way: Be careful when passing callbacks to avoid surprises about what this means in askToReadyRecordVideos. You may use flatMap(() => this.askToReadyRecordVideo()) or flatMap(this.askToReadyRecordVideo.bind(this)) instead of flatMap(this.askToReadyRecordVideo).

Upvotes: 1

Related Questions