Skip to content

Instantly share code, notes, and snippets.

@Stradivario
Last active February 18, 2023 17:41
Show Gist options
  • Save Stradivario/d5e6f96ef4ef400253772b1b5ee88f24 to your computer and use it in GitHub Desktop.
Save Stradivario/d5e6f96ef4ef400253772b1b5ee88f24 to your computer and use it in GitHub Desktop.
Simple operator helping us to render array with delay
import { animationFrameScheduler, from, Observable, of, scheduled } from 'rxjs';
import { bufferCount, concatMap, delay, mergeMap, scan, tap } from 'rxjs/operators';
export const lazyArray =
<T>(delayMs = 0, concurrency = 2, isFirstEmission = true) =>
(source$: Observable<T[]>) =>
source$.pipe(
mergeMap((items) =>
!isFirstEmission
? of(items)
: from(items).pipe(
bufferCount(concurrency),
concatMap((value, index) => scheduled(of(value), animationFrameScheduler).pipe(delay(index * delayMs))),
scan((acc: T[], steps: T[]) => [...acc, ...steps], []),
tap((scannedItems: T[]) => (scannedItems.length === items.length ? (isFirstEmission = false) : null))
)
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment