Rx.Js: understanding expand operator

Viewed 53

I post data to backend, processing data takes some time and long polling is not a solution in my particular case, so I send request each 5 seconds with expand operator

this.apiService.postData(data).pipe(
    expand((status) =>
        status.comptete? this.apiService.askStatus(status.request_id).pipe(delay(5000)) : empty()
    ),
    map((result) => {
        // processing result here
    })
);

The question is how can I make delay be dynamic (e.g. at first time I want to ask for status in 1 second, at second time in 2 seconds and so on)? And two more questions. Have I understood correctly that if I add take(N) operator that will limit askStatus calls to N? Have I understood correctly that I don't need to do any sort of unsubscription here?

1 Answers

expand() passes also index every time it calls the project function so you can calculate delay based on that:

expand((status, index) => 
  status.comptete ? this.apiService.askStatus(...).pipe(delay(...)) : empty()

Using take(N) inside expand() won't help because expand() calls the project function on every emission from both source and inner Observables. But you can of course use take(N) after expand().

You don't have to unsubscribe from askStatus() manually if you handle unsubscription later where you also subscribe.

Related