I'm trying to create an interval observable that waits for the last execution before proceeding. Here are some attempts I've made:
First attempt:
interval(1000)
.subscribe(async x => {
await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10000) + 1000));
console.log('Got counter', x);
});
This resulted in: 4, 1, 2, 6, 9, 7, 6, 3...
Second attempt, but not ideal:
let alreadyRunning = false;
interval(1000)
.pipe(skipWhile(() => alreadyRunning))
.subscribe(async x => {
alreadyRunning = true;
await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10000) + 1000));
console.log('Got counter', x, alreadyRunning);
alreadyRunning = false;
});
The skipWhile operator only waits before the first condition is met.
Next, I tried using switchMap which also did not work:
interval(1000)
.pipe(switchMap(() => from(new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10000) + 1000))))
.subscribe(async x => {
console.log('Got counter', x);
});
Another unsuccessful attempt:
interval(1000)
.pipe(switchMap(x => from(async () => {
await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10000) + 1000));
console.log('Got counter', x);
return x;
})))
.subscribe(async x => {
console.log('X', x);
});
Is there a solution to achieve this? Waiting for the last observable to finish?
//edit 1: What am I looking for?
I have an interval that makes an HTTP Request. If one request takes too long and the next interval starts, it results in multiple requests being executed simultaneously. I want to avoid this scenario.
MergeMap also did not provide the desired outcome:
interval(1000)
.pipe(mergeMap(x => from(new Promise(resolve => setTimeout(() => resolve(x), Math.floor(Math.random() * 10000) + 1000))))
.subscribe(async x => {
console.log('Got counter', x);
});