假设我有一个整数数组,我想在1秒的时间间隔内迭代这个数组,当前秒是数组的索引。一旦索引到达末尾,我想重置间隔值。实现这种行为的正确方法是什么?Stacklitz示例代码:
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
interval(1000)
.pipe(
tap(second => {
if (array[second]) {
console.log(array[second]);
} else {
//reset interval to run in a cyclic manner?
}
})
).subscribe();
所以您想要无限地重复相同的序列。
import { from, of } from "rxjs";
import { concatMap, repeat, delay } from "rxjs/operators";
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
from(array)
.pipe(
concatMap(second => of(second).pipe(
delay(second * 1000),
)),
repeat(),
)
.subscribe(console.log);
现场演示:https://stackblitz.com/edit/rxjs-interval-pmlj6e