DEV Community

Discussion on: What's the RxJs/ NgRx code bit that you are most proud of? (Round 2)

Collapse
 
negue profile image
negue • Edited

This is a timer that only runs if there are entries in an Subject (holding an array), I used it to load/display items after a period of time (instead of having the website render ALL items at once)

  public timer = 100;
  private currentWaitingSubject = new BehaviorSubject([]);
  private interval$$ = this.currentWaitingSubject.pipe(
    filter(ar => ar.length > 0), // only execute when some are waiting
    switchMap(ar => interval(this.timer).pipe( // switch to interval
      withLatestFrom(this.currentWaitingSubject),
      takeWhile(([_, waitingAr]) => waitingAr.length > 0) // until there arent none, auto unsubscribe
    ))
  ).subscribe(([_timer, _currentArray]) => {
    this.currentWaitingSubject.next(
      _currentArray.slice(1)
    );
  });

So how to use this?

Once you have your list of items, you put all IDs into currentWaitingSubject and then subscribe on in and check until that ID you want to show/render isn't anymore in the list (in the Subject)