[英]How to put custom gap between interval for polling in Rxjs angular?
我想在每个间隔调用之间实现间隙/延迟,我在下面尝试过,但它似乎不起作用。
pollOnInterval(threshold = 4000): Observable<any> {
let thresholdValue = threshold;
const increaseBy = 2000;
const maxCount = 10;
return interval(thresholdValue).pipe(take(maxCount)).pipe(delay(increaseBy)).pipe(map(() => {
thresholdValue = thresholdValue + increaseBy;
console.log((new Date).toLocaleTimeString());
}));
}
output
下午 2:34:21
下午 2 点 34 分 25 秒
下午 2:34:29
下午 2:34:33
下午 2:34:37
下午 2 点 34 分 41 秒
下午 2:34:45
下午 2 点 34 分 49 秒
下午 2 点 34 分 53 秒
下午 2:34:57
编辑-1我试过去抖动和去抖动时间,它也没有用,Stackbliz链接: https://stackblitz.com/edit/angular-ivy-tinm4r?file=src%2Fapp%2Fapp.component.ts
编辑 - 2我需要以下方式
下午 2:34:21
下午 2:34:27
下午 2:34:35
您可以 pipe 单个pipe()
中的所有运算符。 每个操作员都不需要自己的 pipe。
正如我在评论中提到的,一旦使用thresholdValue
触发了interval()
,对thresholdValue
变量的后续更改将不会对interval()
function 产生任何影响。 它将在最初由thresholdValue
表示的每个时间间隔内继续发射。
目前 observable 正在发射undefined
s,因为map
没有返回任何内容。
您需要单独使用concatMap
和 pipe 延迟每个发射。 如果不是,则delay
将通过管道传输到整个interval
,如问题中所示。
尝试以下
var { from, of, Observable, interval } = rxjs; var { tap, delay, take, map, concatMap } = rxjs.operators; var displayBox = document.getElementById('display'); function pollOnInterval(threshold = 4000) { let increaseBy = 4000; // delay for first emission from `interval` const maxCount = 10; return interval(4000).pipe( concatMap(value => of(value).pipe( tap(() => displayBox.innerHTML += ` Interval: ${new Date().toLocaleTimeString()}; Delay: ${increaseBy/1000}s <br /> ` ), delay(increaseBy) )), tap(() => increaseBy += 2000), // <-- adjust `increaseBy` take(maxCount), map(() => new Date().toLocaleTimeString()) ); } pollOnInterval().subscribe({ next: value => displayBox.innerHTML += `Subscription: ${value}<br /><hr>`, error: null, complete: () => displayBox.innerHTML += 'Observable complete.' });
<script src="https://unpkg.com/rxjs@6.6.0/bundles/rxjs.umd.min.js"></script> <p id="display"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.