Piping RxJS BehaviorSubject and assigning again to BehaviorSubject

Viewed 73

In my Angular application I have implemented a loading indicator that I can control via an Angular service by setting a BehaviorSubject I called isBusy$. Now I want to set a delay on the BehaviorSubject, so that changes to isBusy$ are only triggers after 500ms.

After reading https://ckjaersig.dk/2020/05/showing-a-loading-spinner-delayed-with-rxjs/ I have come up with the following approach:

  private isBusy$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  private debouncedIsBusy$: Observable<boolean> = this.isBusy$.pipe(debounceTime(500));

With that I can pass debouncedIsBusy$ to Angular's async pipe and it does the job just fine.

While I was experimenting I also tried the following which also seemed to work:

  private isBusy$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false)
    .pipe(
      debounceTime(500)
    ) as BehaviorSubject<boolean>;

In this case a new BehaviorSubject is created then immediately piped which returns a (new?) Observable. Then it is assigned to isBusy$ with the help of as.

I was surprised that this worked as I did not expect the Observable returned by pipe to be an BehaviorSubject. Is this correct code? And if so is it good practice?

Best regards!

0 Answers
Related