1

I have 2 observables like this:

return this.loaded$.pipe(
            switchMap((isLoaded: boolean) => {
                if (!isLoaded) {
                 return this.userId$;
                }
            }),
            tap((userId: string) => {
                this.store.dispatch(new MyPostsList(userId))
            }),
            filter((value: any) => value),
            take(1)
        )

I want to have access to isLoaded var from $loaded stream inside tap part how can I do it? Is it some better way to do this?

Vladimir Djukic
  • 925
  • 2
  • 9
  • 28
  • Your code will error if `isLoaded` is `true`, as `undefined` will be returned to `switchMap`. To answer your question, you'll need to indicate what behaviour is expected in that situation. – cartant Aug 14 '18 at 23:37

1 Answers1

0

You could return an object which contains both the userId and the isLoaded.

return this.loaded$.pipe(
    switchMap(
      (isLoaded: boolean) => Observable.of(
        { userId: (!isLoaded ? this.userId$ : null), isLoaded }
      )
    ),
    tap(({ userId, isLoaded }) => {
      this.store.dispatch(new MyPostsList(userId))
    })
)

As pointed out in the comments, I forgot that switchMap must return an observable. Edited the answer.

Baruch
  • 2,381
  • 1
  • 17
  • 29