Rxjs Repeat Api Call Based On Duration Specified In Response
Context I need to get data from the server that has a variable expiration (specified in the response). Once it expires I need to get it again. So I would like to create a stream th
Solution 1:
This can be easily achieved using the .expand()
operator, which is meant for recursive purposes. The exact solution is only a few lines:
api()
.expand(({expiration}) =>api().delay(expiration))
.take(5)
.subscribe(x=>console.log(x));
Here is the JSBin.
Solution 2:
I am not sure I understood completely your question, but what about something like this
functionapi() {
returnof(Math.random() * 10000);
}
defer(() =>api()).pipe(
tap(delay =>console.log('delay', delay)),
switchMap(data =>interval(data)),
take(5)
).subscribe(console.log);
UPDATED ANSWER AFTER COMMENT
You are already doing the repetition based on what the api is returning to you, and not every 1000 ms. If you run this code it should be clear
let count = 0;
const expiration = Math.random() * 1000;
functionapi() {
returnof({ count, expiration});
}
defer(() =>api()).pipe(
tap(delay =>console.log('delay', delay.expiration)),
switchMap(data =>interval(data.expiration).pipe(map(() => data))),
map(data => ({expiration: data.expiration, count: count++})),
take(5)
).subscribe(console.log);
SECOND UPDATE AFTER SECOND COMMENT
If I understand now what you want to achieve, this should help you
defer(() =>api()).pipe(
tap(data =>console.log('I do something with this data', data)),
switchMap(data =>interval(data.expiration)),
switchMap(() =>api()),
take(5)
).subscribe(data =>console.log('I do something with this data', data));
Post a Comment for "Rxjs Repeat Api Call Based On Duration Specified In Response"