简体   繁体   中英

Identify origin of an observable event on subscription

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?

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 BehaviourSubject s, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM