Łukasz Rzeszotarski
Łukasz Rzeszotarski

Reputation: 6140

Event system ordering issue

In my current project we are using event system which propagates events without priority. What I mean exactly. The problem is that events are called without priority, so it means listening classes fire their 'on message' code in order they were added to listener container.

It can cause sometimes unpredictable difficult to analyze results.

Do you know any existing solutions which handle ordering of events in a 'nice way'?

Upvotes: 1

Views: 199

Answers (3)

Creynders
Creynders

Reputation: 4583

Prioritizing events is the highway to hell. No literally. You'll need to keep track of what objects need what priority. Then you'll run out of priorities. Next you realize you've hard coded the same dependency (the priority constants class) into 100's of classes and literally have tied them all together. Well maybe not, but the pitfalls are numerous and not humorous. You have to look at what you want to achieve: You want to order process execution sequence. It has nothing to do whatsoever with events, except for the completely arbitrary fact that those processes are triggered by events.

There are many solutions:

  1. use a finite state machine, by far the most versatile and clear solution.
  2. isolate the processes that need to be executed in order triggered by one specific event and somehow queue them, for instance use the command pattern and trigger the execution of all commands in the queue by the event. Or using promises is a possibility too.
  3. event chaining the right way: if ClassA needs to respond to event A, but only after ClassB has finished its processing, then ClassA should NOT respond to event A, but to an event dispatched from ClassB. Least preferable of all, but hey sometimes you need to go fast.

Upvotes: 2

BlackJoker
BlackJoker

Reputation: 3191

The PriorityBlockingQueue may do you favor.Make your Event implemetns Comparable,and the event dispatcher thread consume the heighest priority event each time.

Upvotes: 1

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Add a sort-of dependency flag in your listener classes. That is suppose listener A gets called which has a dependency on listener B, then let B execute first. Similarly, you can put dependency conditions in all your listener classes thereby creating a required hierarchy.

Just make sure you don't add circular dependency or handle it carefully.

Upvotes: 1

Related Questions