且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据事件从Observable中获取N个值,直到其完成为止.延迟加载多选列表

更新时间:2023-12-05 17:46:10

此示例生成一个包含450个项目的数组,然后将它们拆分为100的块.它首先转储前100个项目,并且在每次单击按钮后都将另存一个100并将其附加到以前的结果中.加载所有数据后,此链正确完成.

This example generates an array of 450 items and then splits them into chunks of 100. It first dumps the first 100 items and after every button click it takes another 100 and appends it to the previous results. This chain properly completes after loading all data.

我认为您应该能够接受并解决您的问题.使用Subject代替每次单击按钮,每次用户滚动到底部时都会发出Subject:

I think you should be able to take this and use to for your problem. Just instead of button clicks use a Subject that will emit every time user scrolls to the bottom:

import { fromEvent, range, zip } from 'rxjs'; 
import { map, bufferCount, startWith, scan } from 'rxjs/operators';

const SLICE_SIZE = 100;

const loadMore$ = fromEvent(document.getElementsByTagName('button')[0], 'click');
const data$ = range(450);

zip(
  data$.pipe(bufferCount(SLICE_SIZE)),
  loadMore$.pipe(startWith(0)),
).pipe(
  map(results => results[0]),
  scan((acc, chunk) => [...acc, ...chunk], []),
).subscribe({
  next: v => console.log(v),
  complete: () => console.log('complete'),
});

实时演示: https://stackblitz.com/edit/rxjs- au9pt7?file = index.ts

如果您担心性能,则应将trackBy用作*ngFor,以避免重新呈现现有的DOM元素,但我想您已经知道了.

If you're concerned about performance you should use trackBy for *ngFor to avoid re-rendering existing DOM elements but I guess you already know that.