Search code examples
rxjsngrx

Pass the value from WithLatestFrom to another operator - Rxjs, Ngrx effect


I've got this ngrx effect and I want to use the data from my state using withLatestFrom.

$loadProduct = createEffect(() =>
  this.actions$.pipe(
    ofType(fromActions.loadProduct),
    withLatestFrom(this.store.select(fromSelectors.debounceTime)),
    delay(debounceTime), // how can I get the debounceTime value up here?
    map(_ => fromActions.foo())
  )
)

How can I get this debounceTime value within the scope of delay?


Solution

  • How about this:

    $loadProduct = createEffect(() =>
      this.actions$.pipe(
        ofType(fromActions.loadProduct),
        withLatestFrom(this.store.select(fromSelectors.debounceTime)),
        switchMap(([_, debounceTime]) => timer(debounceTime)),
        map(_ => fromActions.foo())
      )
    )
    

    It's using RxJS's switchMap and timer instead of delay.

    By the way, if you do not need the action somewhere in the subsequent part of the pipe, you may also use switchMap instead of withLatestFrom like this:

    $loadProduct = createEffect(() =>
      this.actions$.pipe(
        ofType(fromActions.loadProduct),
        switchMap(() => this.store.select(fromSelectors.debounceTime)),
        switchMap(debounceTime => timer(debounceTime)),
        map(() => fromActions.foo())
      )
    )