In Jetpack Compose, which ViewCompositionStrategy should a ComposeView inside a Fragment use, and what goes wrong with the default strategy?
answer
- when the composition is thrown away
- window detach versus lifecycle destroy
- the Fragment's view outlives a detach
- DisposeOnViewTreeLifecycleDestroyed
- default is DisposeOnDetachedFromWindowOrReleasedFromPool
basics
~10 sUse ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed. The default disposes the composition whenever the ComposeView detaches from the window, so remembered state can be lost while the Fragment's view still exists.
solid answer
~40 sA `ViewCompositionStrategy` decides when a `ComposeView`'s composition is disposed. In Compose 1.12 the default, `ViewCompositionStrategy.Default`, is `DisposeOnDetachedFromWindowOrReleasedFromPool`: it disposes on every window detach unless the view sits in a pooling container such as `RecyclerView`. In a Fragment the `ComposeView` can be detached from the window while the Fragment's view lifecycle is still running, and each detach then throws away the composition and its remembered state; the documentation warns this can cause state loss during incremental migration. `DisposeOnViewTreeLifecycleDestroyed` instead looks up the view-tree `LifecycleOwner` when the view attaches, which for a Fragment's view is its view lifecycle, and disposes at that lifecycle's `ON_DESTROY`. Avoid `DisposeOnLifecycleDestroyed(this)` with the Fragment itself: the Fragment outlives its view on the back stack, so the composition stays alive after the view is gone.
code
kotlin · 16 linesclass LyricsFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = ComposeView(requireContext()).apply {
// Dispose when the Fragment's view lifecycle is destroyed,
// not on every window detach
setViewCompositionStrategy(
ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed
)
setContent {
KaraokeTheme { LyricsScreen() }
}
}
}go deeper
Know that a ComposeView in a Fragment should call setViewCompositionStrategy with DisposeOnViewTreeLifecycleDestroyed before setContent.
Explain the default's window-detach rule with its pooling-container exception, and why a Fragment's view lifecycle is the right signal instead.
Diagnose state lost on detach and compositions leaked by keying disposal to the Fragment, and pick the strategy per host: Fragment, Activity or RecyclerView item.
Set a team rule for every ComposeView host type and enforce it in review or with a shared helper, so disposal is never left to the implicit default.
## What a ViewCompositionStrategy controls A `ComposeView` (or any `AbstractComposeView`) owns a live **composition**: the tree of composables, their remembered values and their registrations with snapshot observers and recomposers. Those registrations can keep the composition, and the views it references, alive long after the host View has been abandoned, so it has to be **disposed** at the right moment. A `ViewCompositionStrategy` is the rule that decides that moment. You set it with `setViewCompositionStrategy(...)` before or after `setContent`, and you can always end the composition early with `disposeComposition()`. ## The four built-in strategies | Strategy | Disposes when | Fits | |---|---|---| | `DisposeOnDetachedFromWindowOrReleasedFromPool` (the `Default`) | the view detaches from a window, unless it is inside a pooling container; then when the pool discards the item or the container itself detaches | a `ComposeView` in an Activity layout, or as a `RecyclerView` item | | `DisposeOnDetachedFromWindow` | every window detach | superseded by the strategy above | | `DisposeOnLifecycleDestroyed(lifecycle)` | the given `Lifecycle` (or `LifecycleOwner`) reaches `ON_DESTROY` | a view with a known 1-1 lifecycle owner | | `DisposeOnViewTreeLifecycleDestroyed` | the `LifecycleOwner` found with `findViewTreeLifecycleOwner()` when the view attaches reaches `ON_DESTROY` | a Fragment's view, or a view whose lifecycle is not known yet | In Compose 1.12 the `Default` property is documented as "currently" `DisposeOnDetachedFromWindowOrReleasedFromPool`, with the note that this implementation detail may change, which is one more reason to set a strategy explicitly where it matters. ## Why the default misbehaves in a Fragment The default ties the composition's life to **window attachment**. A Fragment's view has its own lifecycle, which runs from `onCreateView` to `onDestroyView`, and a view can be detached from the window without that lifecycle ending, for example when a parent View temporarily removes and re-adds its children. Under the default, every such detach disposes the composition; when the view comes back a fresh composition starts and anything held only in `remember` is gone. The Android documentation describes the default as right for a single-Activity Compose app but warns that during incremental adoption it "may cause state loss in some scenarios". `DisposeOnViewTreeLifecycleDestroyed` fixes that: 1. If the view is already attached, it immediately finds the view-tree `LifecycleOwner`; otherwise it waits for the first attach and looks it up then. 2. For a view returned from a Fragment's `onCreateView`, that owner is the **Fragment's view lifecycle**. 3. It observes that lifecycle and calls `disposeComposition()` on `ON_DESTROY`, which the Fragment dispatches as its view is torn down, just before `onDestroyView()`. Because the lookup happens at attach time, the strategy can be set inside `onCreateView`, before the Fragment's view lifecycle owner is available. ## Mistakes with the lifecycle-based strategies - **Passing the Fragment itself** to `DisposeOnLifecycleDestroyed`. A Fragment on the back stack keeps living after `onDestroyView`, so the composition stays live and keeps references to a view tree that will never be shown again: a leak until the Fragment is destroyed. - **No view-tree owner.** `DisposeOnViewTreeLifecycleDestroyed` throws `IllegalStateException` ("View tree for ... has no ViewTreeLifecycleOwner") when the attached view tree has no owner. - **An owner that is already destroyed.** Installing either lifecycle strategy against a `Lifecycle` already in `DESTROYED` throws `IllegalStateException`. ## A worked timeline Take a karaoke-booking app whose lyrics screen is a Fragment returning a `ComposeView`. The user opens the lyrics, the `ComposeView` is briefly removed and re-added by a parent View that reorders its children, and later the user navigates to the booking Fragment, which replaces the lyrics Fragment and puts it on the back stack. | Event | Default strategy | `DisposeOnViewTreeLifecycleDestroyed` | `DisposeOnLifecycleDestroyed(fragment)` | |---|---|---|---| | View detached and re-attached | composition disposed, then rebuilt; `remember` state lost | composition kept | composition kept | | Fragment replaced, view destroyed | disposed on detach | disposed at the view lifecycle's `ON_DESTROY` | still alive, holding the dead view tree | | User presses Back, new view created | fresh composition | fresh composition | fresh composition, while the old one stays alive until the Fragment is destroyed | Only the view-tree strategy gets both rows right: it survives a detach that is not the end of the view, and it ends exactly when the Fragment's view ends. State that must outlive the view itself, such as the selected verse, belongs in the screen's `ViewModel` or in saved state, not in `remember`. ## When to keep the default - A `ComposeView` used as a `RecyclerView` item: the default understands the **pooling container**, so the composition survives recycling and is disposed only when the pool discards the item or the list itself detaches. - A single-Activity, Compose-first app where window detach really means the UI is gone. ## Summary - Fragment's view: `DisposeOnViewTreeLifecycleDestroyed`. - `RecyclerView` item or plain Activity layout: the default. - Never key disposal to the Fragment's own lifecycle.
- Why not call DisposeOnLifecycleDestroyed(viewLifecycleOwner) directly inside onCreateView?The Fragment's view lifecycle owner is not available until `onCreateView` has returned the view. `DisposeOnViewTreeLifecycleDestroyed` defers the lookup to the moment the view attaches, when the view-tree owner, the view lifecycle, is in place. Using `DisposeOnLifecycleDestroyed(viewLifecycleOwner)` later, for example in `onViewCreated`, is equivalent.
- Which strategy should a ComposeView used as a RecyclerView item use?Keep the default, `DisposeOnDetachedFromWindowOrReleasedFromPool`. Inside a pooling container it does not dispose on each detach, so a recycled item keeps its composition; it disposes when the pool discards the item or the `RecyclerView` itself detaches. Detach-only disposal would rebuild the composition on every scroll.
- How can you end a ComposeView's composition earlier than its strategy would?Call `disposeComposition()` on the view. A new composition is created automatically the next time it is needed, for example when the view is attached or measured again, so it is safe to use when a long-lived view is being retired.
- The default strategy already follows the Fragment's view lifecycle
- Passing the Fragment itself to DisposeOnLifecycleDestroyed is the safest choice
- DisposeOnDetachedFromWindow is the current default for ComposeView
- A ComposeView's composition is garbage collected without any disposal strategy
- A RecyclerView item ComposeView should use DisposeOnViewTreeLifecycleDestroyed
Assumes Compose UI 1.12, where ViewCompositionStrategy.Default is DisposeOnDetachedFromWindowOrReleasedFromPool; its KDoc says this default may change.