Home > Software engineering >  Identify origin of an observable event on subscription
Identify origin of an observable event on subscription

Time:09-26

I have a BehaviorSubject<Array<user>> (userListSub$) state that is updated from various places.

For example,

  • when I click Follow on a user
  • when I click Unfollow on a user
  • when I favorite a user

The same state is being subscribed in different components. I would like a particular component to not react to an event emitted by the state (userListSub$) if the event was triggered when I favorite the user.

I know we can store the origin of the event also in the state like this,
userListSub$.next({ data: user, origin: userList })
and check for the origin where I subscribe.

Is there a better way to identify or ignore the event on particular subscriptions?
Am I thinking in the right direction? If not, can you suggest a better way?

CodePudding user response:

You may to try a slightly different model.

Suppose you have 3 components: C1, C2 and C3. All the components react to the events "Click Follow on a user" and "Click Unfollow on a user".

Only C1 and C2 though react to the event "favorite a user".

In this case, you can model 2 streams of events, and therefore 2 BehaviourSubjects, let's call them S1 and S2, one that notifies "Click Follow on a user" and "Click Unfollow on a user" events and the other that notifies the "favorite a user" event.

Then you can create an Observable, let's call it Obs1 = merge(S1, S2) that merges S1 and S2.

Now, C1 and C2 can subscribe to Obs1 while C3 can subscribe to S1.

In this way you should be able to achieve your objective and, at least in my opinion, this is a more idiomatic reactive way to achieve it than adding the id of the source.

  • Related