Using Component Lifecycle Callbacks

If the content of a component depends on resources that are not available during the construction of the component, you can postpone content creation until the component attaches to the UI, by overriding the onAttach() method (provided by the Component class).

Example: Overriding the onAttach method.

Java

  1. @Tag("div")
  2. public class UserNameLabel extends Component {
  3. @Override
  4. protected void onAttach(AttachEvent attachEvent) {
  5. // user name can be stored to session after login
  6. String userName = (String) attachEvent.getSession()
  7. .getAttribute("username");
  8. getElement().setText("Hello " + userName +
  9. ", welcome back!");
  10. }
  11. }

The onAttach method is invoked when the Component has attached to the UI. Its counterpart, the onDetach method, is invoked right before the component detaches from the UI. These are good times to reserve and release resources used by the component.

Example: Overriding the onAttach and onDetach methods.

Java

  1. @Tag("div")
  2. public class ShoppingCartSummaryLabel
  3. extends Component {
  4. private final Consumer<EventObject> eventHandler =
  5. this::onCartSummaryUpdate;
  6. @Override
  7. protected void onAttach(AttachEvent attachEvent) {
  8. ShopEventBus eventBus = attachEvent.getSession()
  9. .getAttribute(ShopEventBus.class);
  10. // registering to event bus for updates
  11. // from other components
  12. eventBus.register(eventHandler);
  13. }
  14. @Override
  15. protected void onDetach(DetachEvent detachEvent) {
  16. ShopEventBus eventBus = detachEvent.getSession()
  17. .getAttribute(ShopEventBus.class);
  18. // after detaching don't need any updates
  19. eventBus.unregister(eventHandler);
  20. }
  21. private void onCartSummaryUpdate(EventObject event) {
  22. // update cart summary ...
  23. }
  24. }
  25. interface ShopEventBus {
  26. void register(Consumer<EventObject> eventHandler);
  27. void unregister(Consumer<EventObject> eventHandler);
  28. }
  • Using methods available in attachEvent and detachEvent to get the UI or session is more convenient than using the getUI() method in Component, because these methods return values directly. The getUI() method returns an Optional<UI>, because a component is not always attached.

  • The default implementations of the onAttach and onDetach methods are empty, so you don’t need to call super.onAttach() or super.onDetach() from your overridden methods. However, when extending other component implementations you may need to do this.

Tip
To find out when another component gets attached or detached, you can use the Component.addAttachListener and Component.addDetachListener methods. The corresponding events are fired after the onAttach and onDetach methods are invoked. The getUI() method for the component will return the UI instance during both events.