Lifecycles
Sometimes we need to react to specific events or actions that happen within a component.
Spigot, Paper, and BungeeCord use events to signalize the entire plugin that something has now happened.
The plugin can create event listeners to listen to these events and perform actions when they occur.
But sometimes we don't want the entire plugin to randomly handle the event of a specific component that just gets messy and unorganized with a growing code base.
To keep things tidy, Vital uses an approach called lifecycles.
Sounds complicated but is very simple to understand and use.
Basically, specific components like commands, inventories, configs, repositories, etc. may expose ways to "intercept" an action that is currently happening.
Just like you would intercept plugin startup in a normal plugin using onEnable.
Let's say you are building an inventory and want to react to a click within that inventory.
Normally, you would create an event listener for the entire plugin, and then manually filter out events that should only be handled when you clicked your specific inventory.
@EventHandler
public void onInventoryClick(InventoryClickEvent e) {
if (e.getClickedInventory() == null || !(e.getClickedInventory().getHolder() instanceof MyCustomInventory)) {
return;
}
// Handle inventory event for MyCustomInventory.
}
But this is just bad design...
What happens if we want to handle another inventory, we'd have to make another branch, eventually we'd end up with a code base that is not readable anymore...
To ensure this doesn't happen, Vital scopes your events for specific lifecycles to your component automatically.
@VitalInventory.Info(...)
public class MyCustomInventory extends VitalInventory {
@Override
public void onClick(InventoryClickEvent e) {
// Handle inventory event for MyCustomInventory.
}
}
This onClick lifecycle will only be called when you actually click this inventory.
Nothing extra, just handling this lifecycle... easy!
Lifecycles are not only available for inventories, they are used by the entire code base of Vital.
Each lifecycle will always have the on... prefix.
To see which lifecycles are available for your component, check the Javadoc, use your IDEs autocompletion when typing on, or simply check the documentation of your component on this site.