[英]Identify origin of an observable event on subscription
I have a BehaviorSubject<Array<user>>
( userListSub$
) state that is updated from various places.我有一个从各个地方更新的
BehaviorSubject<Array<user>>
( userListSub$
) state。
For example,例如,
The same state is being subscribed in different components.在不同的组件中订阅了相同的 state。 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.如果在我喜欢用户时触发了事件,我希望特定组件不对 state (
userListSub$
) 发出的事件做出反应。
I know we can store the origin of the event also in the state like this,我知道我们也可以像这样将事件的起源存储在 state 中,
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.您可以尝试稍微不同的 model。
Suppose you have 3 components: C1, C2 and C3.假设您有 3 个组件:C1、C2 和 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".尽管只有 C1 和 C2 对“收藏用户”事件做出反应。
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.在这种情况下,您可以 model 2 个事件流,因此 2 个
BehaviourSubject
,我们称它们为S1
和S2
,一个通知“点击用户”和“点击取消关注用户”事件,另一个通知“收藏用户”事件。
Then you can create an Observable
, let's call it Obs1 = merge(S1, S2)
that merges S1
and S2
.然后你可以创建一个
Observable
,我们称之为Obs1 = merge(S1, S2)
合并S1
和S2
。
Now, C1 and C2 can subscribe to Obs1
while C3 can subscribe to S1
.现在,C1 和 C2 可以订阅
Obs1
而 C3 可以订阅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.通过这种方式,您应该能够实现您的目标,并且至少在我看来,这是一种比添加源代码更惯用的反应方式来实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.