Skip to content Skip to sidebar Skip to footer

How To Deal With Race Conditions In Event Listeners And Shared State?

I have 2 event listeners that operate on the same shared data/state. For instance: let sharedState = { username: 'Bob', isOnline: false, }; emitter.on('friendStatus', (status)

Solution 1:

From @Bergi's answer in the comments the solution I was hinting seems to be the most appropriate for such case. Simply let the event-handlers set their own independent state, then observe on the values changing and write appropriate logic based on what you need to do. For instance I need to show a username; this function shouldn't care about the order or have any knowledge of time: it should simply check whether the isOnline status is true and if there's a username. Then the observable pattern can be used to call this function whenever each dependency of the function changes. In this case the function depends on status.isOnline and friend.username hence it will observe and re-execute whenever those values change.

functionshowUsername() {
  if (status.isOnline && friend.username != '') returntrue;
}

This function must observe the properties it depends on (status.isOnline and friend.username). You can have a look at RxJS or other libraries for achieving this in a more "standard" way.

Post a Comment for "How To Deal With Race Conditions In Event Listeners And Shared State?"