ngxtension / ngxtension-platform

Utilities for Angular
https://ngxtension.netlify.app/
MIT License
544 stars 80 forks source link

Add a new RxJS utility function to create a `repeat` operator with an internal subject #380

Closed LcsGa closed 2 weeks ago

LcsGa commented 2 months ago

I thougt of this tool while working on a side project as I repeated this kind of logic:

@Component({
  ...,
  template: `
    ...
    <!-- diplayed on error -->
    <button (click)="retry()">Retry</button>
  `
})
export class Comp {
  readonly #service = inject(MyService);

  readonly retry$ = new Subject<void>();

  readonly #register = rxEffect(this.#service.register$.pipe(
    // custom operator with a map (data), startwith (pending), catchError (error) + a short debounceTime to avoid flashings
    toState(),
    repeat({ delay: () => this.#repeat$ })
  ));

  // Whereas it is a repeat, the retry name comes from the logic itself
  retry() {
    this.retry$.next();
  }
}

=> I had to repeat the subject everytime I needed this repeat operator, and as I don't want to let subjects public, I also had to wrap the next logic within a method + to use that subject inside of a repeat operator and it felt like I could simplify that with a custom createRepeat function:

@Component({
  ...,
  template: `
    ...
    <!-- diplayed on error -->
    <button (click)="retry.emit()">Retry</button>
  `
})
export class Comp {
  readonly #service = inject(MyService);

  // the cool part here is that you can name your operator as you want
  readonly retry = createRepeat();

  readonly #register = rxEffect(this.#service.register$.pipe(toState(), this.retry()));
}

NB: I also plan to add a createRetry