Search code examples
androidandroid-fragmentsandroid-activityandroid-lifecycle

What is the difference between overriding lifecycle methods of activity or fragment and adding a LifecycleObserver to its lifecycle object?


I was reading developer.android documents (this page) and encountered this paragraph :

Do not override lifecycle methods such as onResume in Activities or Fragments. Use LifecycleObserver instead. If the app needs to perform work when the lifecycle reaches a certain Lifecycle.State, use the repeatOnLifecycle API.

My question is, What is the difference between overriding lifecycle methods of an activity or fragment and adding a LifecycleObserver to its lifecycle object?

It is for making the code cleaner and nicer or are there some perfomance-related reasons or prevention of errors and bugs, and so on?


Solution

  • My question is, What is the difference between overriding lifecycle methods of an activity or fragment and adding a LifecycleObserver to its lifecycle object? It is for making the code cleaner and nicer or are there some perfomance-related reasons or prevention of errors and bugs, and so on?

    There is no functional difference. Using LifecycleObserver is the new hotness. Overriding lifecycle methods is the old coldness.

    Why?

    In the early days of Android, the Android platform team basically threw every possible callback and functionality into Activity leading developers that didn't know any better to put all their logic into their Activity subclasses, resulting in "god" classes that were thousands of lines longs, did 42 different things, and were fundamentally untestable and unmaintable.

    Nowadays they're implementing better software engineering practices and breaking out the responsibilites of the Activity. In this case, instead of the Activity being responsible for handling all the lifecycle events, it delegates the events to any objects that are interested in being aware of said events. These objects don't have to know anything about Activity - they just know that some event happens - allowing them to be far more composable, reusable, and testable.