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 underlyingComposeViewis detached from the window. Has since been superseded byDisposeOnDetachedFromWindowOrReleasedFromPool.Interop scenario:
ComposeViewwhether 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:
ComposeViewwhether it’s the sole element in the View hierarchy, or in the context of a mixed View/Compose screen (not in Fragment);ComposeViewas an item in a pooling container such asRecyclerView.
-
DisposeOnLifecycleDestroyed. The Composition will be disposed when the providedLifecycleis destroyed.Interop scenario:
ComposeViewin a Fragment’s View.
-
DisposeOnViewTreeLifecycleDestroyed. The Composition will be disposed when the
Lifecycleowned by theLifecycleOwnerreturned byViewTreeLifecycleOwner.getof the next window the View is attached to is destroyed.Interop scenario:
ComposeViewin a Fragment’s View;ComposeViewin a View wherein the Lifecycle is not known yet.
Links
Further Reading
ViewCompositionStrategy Demystified