Sometimes we would like the component to subscribe a listener when it's available and unsubscribe the listener when the component is unavailable. Usually we can use
InvisibleEvent handlers to subscribe/unsubscribe listeners.
However, there're a few drawbacks with this approach:
VisibleEventhandler might not be called because the component isn't visible in the viewport, or might be called multiple times without changing the component. Similar issue with
InvisibleEventhandler. It's hard to use these event handlers to manage listeners/resources.
- There's no guarantee that
InvisibleEventhandlers are executed in order.
Method annotated with
@OnAttached is called when the component is attached to the
ComponentTree, and method annotated with
@OnDetached is called when either it's removed from the
ComponentTree or the
ComponentTree is released. For each component, both the methods are guaranteed to be called at most once.
By introducing these two methods, now we can subscribe the listener in
@OnAttached method and unsubscribe it in
@OnAttached is called when
LayoutState is finalized and applied to the
ComponentTree. For each component in each
@OnAttached is guaranteed to be called only once.
@OnDetached is called either when
ComponentTree#release()is called. Usually you would need to release
ComponentTreemanually in Activity/Fragment
- A new root is assigned to
ComponentTree#setRoot()or one of their async variants is called, and the old component doesn't exist in the root. For example:
When a new root is applied,
@OnDetached methods for components
E are called. You can see that even if component
E still exists in the new root, its
@OnDetached is called as well, because its position has changed.
Check out Component Lifecycle Example in our sample app to understand the component lifecycle methods better!