Skip to content

Commit

Permalink
DEV: add debounce to component spinner
Browse files Browse the repository at this point in the history
  • Loading branch information
anuradhawick committed Dec 9, 2024
1 parent a094ce6 commit ccfc777
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@if (loading) {
@if (localLoading | async) {
<div class="bui-loading-container">
<div class="bui-loading-shade">
<img height="100px" src="/assets/images/spinner.gif" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,55 @@
import { Component, Input } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { OnChanges, SimpleChanges } from '@angular/core';
import {
debounce,
distinctUntilChanged,
map,
Observable,
pairwise,
startWith,
Subject,
timer,
} from 'rxjs';

@Component({
selector: 'app-component-spinner',
templateUrl: './component-spinner.component.html',
styleUrls: ['./component-spinner.component.scss'],
imports: [AsyncPipe],
standalone: true,
})
export class ComponentSpinnerComponent {
export class ComponentSpinnerComponent implements OnChanges, OnInit, OnDestroy {
@Input()
loading: boolean = false;
localLoading: Observable<boolean> = new Observable<boolean>();
private loadingSubject = new Subject<boolean>();

ngOnChanges(changes: SimpleChanges): void {
if (changes['loading']) {
this.loadingSubject.next(this.loading);
}
}

/**
* Lifecycle hook that is called after data-bound properties of a directive are initialized.
* Initializes the localLoading observable by subscribing to the loadingSubject observable.
*
* The localLoading observable:
* - Starts with a value of false.
* - Emits values only when they change.
* - Emits a value after a debounce period, which is 1000ms if the previous value was true, otherwise 0ms.
* - Maps the emitted pair to the current value.
*/
ngOnInit(): void {
this.localLoading = this.loadingSubject.pipe(
startWith(false),
distinctUntilChanged(),
pairwise(),
debounce(([prev, _]) => (!!prev ? timer(1000) : timer(0))),
map(([_, curr]) => curr),
);
}

ngOnDestroy(): void {}
}

0 comments on commit ccfc777

Please sign in to comment.