msqar
msqar

Reputation: 3020

How to avoid automatic subscription of observables after combineLatest?

Let's say I got 2 observables.

obsA => this.usersList$
obsB => a function that returns an observable

I'm using the combine like this:

   return combineLatest([this.getIdFromUser$(id), this.usersList$]).pipe(
      map(([user, userList]) => {
          ... here I call another function that will at the end, add a new user to the 
              observable list.
      })
   );

This combineLatest is being triggered after a click subject. When usersList$ observable is updated, the whole chain gets called again, even if I didn't click again, just because one observable of the chain changed.

How can I prevent this from happening? I don't want to unsuscribe to the whole thing, as you can actually keep clicking a button to change the state of the button (toggle it).

Upvotes: 0

Views: 375

Answers (1)

TotallyNewb
TotallyNewb

Reputation: 4790

As noted in the comment under your question, you could go with:

return this.getIdFromUser$(id)
    .pipe(
        withLatestFrom(this.usersList$),
        map(([user, userList]) => {
          ... here I call another function that will at the end, add a new user to the observable list.
      })
    );

This will emit every time this.getIdFromUser$(id) emits (which I assume happens on the mentioned click event), but only after this.usersList$ has emitted at least once. It will always contain latest value of this.usersList$.

Upvotes: 1

Related Questions