Fragment Lifecycle Flashcards

ANDROID › Lifecycle

Why observe LiveData with viewLifecycleOwner instead of the fragment (this)?
The view can be destroyed (onDestroyView) while the fragment instance survives on the back stack. Observing with the fragment keeps the observer and its captured view references alive past onDestroyView, leaking the old view; viewLifecycleOwner auto-removes the observer when the view is destroyed.
What are the five Lifecycle.State values a fragment moves through?
INITIALIZED, CREATED, STARTED, RESUMED, and DESTROYED. The fragment climbs up to RESUMED and back down to DESTROYED, never re-entering INITIALIZED once it leaves it.
Why does a fragment have a separate view lifecycle from the fragment lifecycle?
A back-stacked fragment keeps its instance (fragment lifecycle alive at CREATED) but destroys its view via onDestroyView when replaced, then recreates it via onCreateView when returning. The view's lifecycle therefore starts and ends multiple times within one fragment lifecycle.
When is viewLifecycleOwner valid, and what happens if you access it outside that window?
It is valid only between onCreateView returning a non-null view and onDestroyView. Accessing it before onCreateView or after onDestroyView throws IllegalStateException, since no view lifecycle exists then.
Give the downward callback order when a fragment leaves the screen and is destroyed.
onPause, onStop, onDestroyView, onDestroy, onDetach. onDestroyView runs before onDestroy because the view tears down first, and onDetach is always last.
What three things cap a fragment's maximum lifecycle state?
Its host FragmentManager's state, an explicit FragmentTransaction.setMaxLifecycle() cap, and its parent in the hierarchy (a child can never exceed its parent fragment/activity state). A fragment can never be more resumed than its host.
What should you do with view binding references in onDestroyView, and why?
Set the binding (and any view references) to null. The view is destroyed but the fragment instance may live on the back stack, so retaining the binding leaks the entire destroyed view tree.
How do replace() with addToBackStack vs without differ for the fragment's lifecycle?
With addToBackStack the old fragment is stopped and its view destroyed (onDestroyView) but the instance is retained at CREATED, so pressing Back recreates its view. Without addToBackStack the old fragment is fully destroyed (onDestroy, onDetach) and removed.
Why must you collect a Flow in a fragment with repeatOnLifecycle(viewLifecycleOwner)?
viewLifecycleOwner.lifecycleScope plus repeatOnLifecycle(STARTED) ties collection to the view being visible, cancelling when the view stops and restarting when it returns. Using the fragment's lifecycleScope would keep collecting and updating a destroyed view, leaking it.

Back to Fragment Lifecycle