【发布时间】:2021-08-28 11:32:15
【问题描述】:
我想要一个等待最后一次执行的可观察间隔。 这是我的尝试。
不等待的简单事情。
interval(1000)
.subscribe(async x => {
await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10000) + 1000));
console.log('Got counter', x);
});
结果:4, 1, 2, 6, 9, 7, 6, 3, ...
下一次尝试,但有点糟糕。
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;
});
skipWhile 只等待在第一件事为真之前。
现在我尝试了同样不起作用的 switchMap。
interval(1000)
.pipe(switchMap(() => from(new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10000) + 1000)))))
.subscribe(async x => {
console.log('Got counter', x);
});
也不行:
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);
});
是否有解决方案来实现这一点?等待最后一个 observable 完成? 订阅后没有机会这样做。 那么我以前怎么能做到这一点。
//编辑1: 我想要什么?
我有一个在其中执行 HTTP 请求的间隔。 因此,当 HTTP 请求等待几秒钟时,将执行下一个间隔,以便多次执行请求。
我想避免的。
MergeMap 也不起作用。
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);
});
【问题讨论】:
-
抱歉,Patrick,我看到你努力详细地写下你的问题,但不清楚你在问什么或你想要什么。例如,在您的任何示例中都没有最后的排放,那么您怎么能等待呢?
-
我说得对吗,目标是发射从 0 到无穷大的不断增加的值,但在下一次发射前等待随机时间?
-
我同意 Daniel Gimenez 的观点,我不太了解您正在寻找的行为。你能澄清一下吗?
-
interval$.pipe( skipUntil( observable$.pipe(last()) ) ) -
@DanielGimenez 我有一个 http 请求,希望等到最后一个请求完成。我更新了文字。希望它更清楚?像 Promise.resolve().then().then().then() 我需要 Observable.interval(1000).subscribe(async () => { WAIT FOR LAST ASYNC })。
标签: javascript angular typescript rxjs observable