0

My concern is that isn't creating an own class for each and every unique event considered bad practice? Feels like this approach is not sophisticated, even more so if i have dozens of events. Although it's an easy solution (unique fields for every event type) but comes with lots of almost empty classes.

I'd rather have a generalized class and one @Subscribe-d method in which i can check the type of message sent (with an enum) and then act accordingly, but this approach requires me to create for example a map and put data inside it and then pass this map every time i want to post something, which also does not seem to be the best way to go.

What do you think?

chrystolin
  • 1,067
  • 1
  • 9
  • 17

1 Answers1

1

Checking for a type of event inside the event goes somewhat against the design philosophy of Otto and OOP in general. If the events are separate, post them as separate classes and subscribe to them in different methods.

The idea of an event bus is to decouple producers and consumers. Event type checking in consumer increases coupling and makes the code less efficient and harder to maintain.

Empty classes will work just fine. You can group related event classes together e.g. as static inner classes.

If you only need to post an enum value such as broadcasting state changes in the app, you can use the enum type when posting/subscribing. No need for a class there.

For passing around data, you can post the object that contains the data. You don't need to create new objects each time, just update the data in-place and repost the same object.

Some developers post "data changed" events and have the consumers then fetch the updated data from the producer itself. That again introduces additional coupling between consumers and producers and I'd avoid that.

laalto
  • 150,114
  • 66
  • 286
  • 303