ViewCompositionStrategy
ViewCompositionStrategy
defines when the Composition should be disposed. The default, ViewCompositionStrategy.Default
, disposes the Composition when the underlying ComposeView
detaches from the window, unless it is part of a pooling container such as a RecyclerView
. In a single-Activity Compose-only app, this default behavior is what you would want, however, if you are incrementally adding Compose in your codebase, this behavior may cause state loss in some scenarios.
To change the ViewCompositionStrategy
, call the setViewCompositionStrategy()
method and provide a different strategy.
There are four different options for ViewCompositionStrategy
:
-
DisposeOnDetachedFromWindow
. The Composition will be disposed when the underlyingComposeView
is detached from the window. Has since been superseded byDisposeOnDetachedFromWindowOrReleasedFromPool
.Interop scenario:
ComposeView
whether it’s the sole element in the View hierarchy, or in the context of a mixed View/Compose screen (not in Fragment).
-
DisposeOnDetachedFromWindowOrReleasedFromPool
(Default). Similar toDisposeOnDetachedFromWindow
, when the Composition is not in a pooling container, such as aRecyclerView
. If it is in a pooling container, it will dispose when either the pooling container itself detaches from the window, or when the item is being discarded (i.e. when the pool is full).Interop scenario:
ComposeView
whether it’s the sole element in the View hierarchy, or in the context of a mixed View/Compose screen (not in Fragment);ComposeView
as an item in a pooling container such asRecyclerView
.
-
DisposeOnLifecycleDestroyed
. The Composition will be disposed when the providedLifecycle
is destroyed.Interop scenario:
ComposeView
in a Fragment’s View.
-
DisposeOnViewTreeLifecycleDestroyed. The Composition will be disposed when the
Lifecycle
owned by theLifecycleOwner
returned byViewTreeLifecycleOwner.get
of the next window the View is attached to is destroyed.Interop scenario:
ComposeView
in a Fragment’s View;ComposeView
in a View wherein the Lifecycle is not known yet.
Links
Further Reading
ViewCompositionStrategy
Demystified