如何为间隔的每次迭代设置randomIntervals的值?
import {random} from 'lodash'
import {interval, timer} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
const timer$ = timer(5000);
const randomInterval = random(100, 1000);
const source = interval(randomInterval)
.pipe(
takeUntil(timer$)
);
source.subscribe(console.log)
答案 0 :(得分:1)
那呢?零间隔,它会随机延迟返回项目。
const { interval, of } = rxjs;
const { concatMap, delay } = rxjs.operators;
interval(0).pipe(
concatMap(i => of(i).pipe(delay(Math.random() * 5000)))
).subscribe(val => { console.log(val); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
答案 1 :(得分:0)
我认为您不能指定随机间隔,但可以使用超时
const { BehaviorSubject } = rxjs;
const random$ = new BehaviorSubject(1);
random$.subscribe(val => { console.log(val); });
random();
function random() {
random$.next(random$.getValue() + 1);
setTimeout(random, Math.random() * 5000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
或者有这个答案
RXJS: How can I generate a stream of numbers at random intervals (within a specified range)?