What is eventbus?
An event bus is a simple communication system that lets different parts of a program send and receive messages (called events) without needing to know about each other. Think of it like a central “bus stop” where one component can shout out a message, and any other component that’s listening can hear it and react.
Let's break it down
- Event: A piece of information that something happened (e.g., a button was clicked, data was loaded).
- Publisher: The part of the code that creates (publishes) the event and puts it on the bus.
- Subscriber: The part of the code that listens for specific events and runs code when they arrive.
- Bus: The middleman that holds the list of subscribers and delivers events from publishers to them.
Why does it matter?
Using an event bus keeps code loosely coupled. That means you can add, remove, or change features without rewriting large sections because components talk through the bus instead of directly to each other. It also makes it easier to handle asynchronous actions, like waiting for a server response, without blocking the rest of the app.
Where is it used?
- Front‑end frameworks (e.g., Vue.js, Angular) for component communication.
- Mobile apps (e.g., Android’s EventBus library) to pass data between activities or fragments.
- Desktop applications that need plugins or modules to interact.
- Game engines for broadcasting game state changes (score updates, level completion).
Good things about it
- Loose coupling: Components don’t need to know each other’s internals.
- Scalability: Adding new listeners is as easy as registering them.
- Simplifies async flow: Events can be emitted now and handled later.
- Centralized debugging: You can monitor all events in one place.
Not-so-good things
- Harder to trace: Because communication is indirect, it can be tricky to follow the flow of data.
- Potential for memory leaks: Forgetting to unsubscribe listeners can keep objects alive longer than needed.
- Overuse leads to chaos: If every tiny action becomes an event, the bus gets noisy and hard to manage.
- Performance hit: Excessive events can slow down the app, especially on low‑end devices.