我正在尝试制作一个 Observable,它在单击按钮时发出一个 PAGE_SIZE
数组(第一次单击应该发出 [0, 1, 2, 3, 4]
),需要注意的是,在单击按钮后,间隔将开始发出更多与原始数字相连的数字(即,在用户单击间隔后,间隔应发出 [0, 1, 2, 3, 4 , 5, 6, 7, 8, 9]
,然后是 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
等)。
以下内容几乎可以满足我的要求,但我需要整个过程在用户再次单击按钮时重新开始。
有什么想法吗?
const PAGE_SIZE = 5;
let currentPage = 0;
const buttonEl = document.getElementsByTagName('button')[0];
const refreshSource$ = new rxjs.Subject().pipe(rxjs.operators.concatMap(() => rxjs.interval(5000)));
const clickSource$ = new rxjs.fromEvent(buttonEl, 'click').pipe(rxjs.operators.tap(() => {
refreshSource$.next();
refreshSource$.complete();
}));
const clips$ = rxjs.merge(clickSource$, refreshSource$).pipe(rxjs.operators.mergeMap(value => {
if (value.type === undefined)
return makeObservable(value + 1);
else
return makeObservable(0);
}), rxjs.operators.scan((acc, value) => acc.concat(value)), rxjs.operators.startWith([]));
clips$.subscribe(value => {
console.log('clips$', value);
});
function makeObservable(page) {
return rxjs.of(d3.range(page * PAGE_SIZE, (page + 1) * PAGE_SIZE));
}
最佳答案
您需要的是在每次点击时将 switchmap 切换到一个新的可观察对象,重新开始生成您的数组:
import { interval, fromEvent } from 'rxjs';
import { switchMap, take, map } from 'rxjs/operators';
const buttonEl = document.getElementById('button');
const pagesize = 5;
fromEvent(buttonEl, 'click')
.pipe(
// restart counter on every click
switchMap(() =>
interval(500).pipe(take(5))
),
map(i => {
const max = (i+1) * pagesize;
return Array.from(Array(max).keys());
})
)
.subscribe(console.log);
(堆栈 Blitz :https://stackblitz.com/edit/rxjs-v85ctu?file=index.html)
有关 switchMap 运算符的完整引用,请参阅:https://www.learnrxjs.io/operators/transformation/switchmap.html
关于javascript - 重置嵌套的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070750/