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.

@Tag("div")
public class UserNameLabel extends Component {

  @Override
  protected void onAttach(AttachEvent attachEvent) {
    // user name can be stored to session after login
    String userName = (String) attachEvent.getSession()
            .getAttribute("username");
    getElement().setText("Hello " + userName +
            ", welcome back!");
  }
}

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.

@Tag("div")
public class ShoppingCartSummaryLabel
        extends Component {

  private final Consumer<EventObject> eventHandler =
        this::onCartSummaryUpdate;

  @Override
  protected void onAttach(AttachEvent attachEvent) {
    ShopEventBus eventBus = attachEvent.getSession()
            .getAttribute(ShopEventBus.class);
    // registering to event bus for updates
    // from other components
    eventBus.register(eventHandler);
  }

  @Override
  protected void onDetach(DetachEvent detachEvent) {
    ShopEventBus eventBus = detachEvent.getSession()
    .getAttribute(ShopEventBus.class);
    // after detaching don't need any updates
    eventBus.unregister(eventHandler);
  }

  private void onCartSummaryUpdate(EventObject event) {
    // update cart summary ...
  }
}

interface ShopEventBus {
  void register(Consumer<EventObject> eventHandler);

  void unregister(Consumer<EventObject> eventHandler);
}
  • 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.