Interop: Compose in Views and Views in Compose
Why it matters
- Production codebases carry years of View code; you cannot rewrite every screen in one sprint, so interop is the only realistic migration path.
- Interviewers ask how you would migrate a screen and what the runtime cost of mixing the two systems is.
- A wrong ViewCompositionStrategy either keeps a composition alive after its view is gone (a leak) or disposes it too early (lost state).
- AndroidView's
updateblock can run many times. Heavy work there causes frame drops users feel as jank.
The simple explanation
- Renovating a house room by room instead of demolishing it.
ComposeViewis a new room built inside the old house (the View tree).AndroidViewis an old appliance (a legacy View) plugged into the new room (a Compose layout).factoryis the electrician who installs the appliance once.updateis the daily check that the appliance is still connected and set correctly.onReleaseis unplugging and removing the appliance when the room is torn down.
Two bridges let you mix Compose and Views on the same screen.
Views hosting Compose: ComposeView
ComposeView (in androidx.compose.ui.platform) is a View subclass. Call setContent { } to add a Compose tree. You can create it in code or put it in an XML layout. Its viewCompositionStrategy controls when the composition is disposed.
Compose hosting Views: AndroidView
AndroidView (in androidx.compose.ui.viewinterop) is a @Composable that creates a View inside a Compose layout. Its main lambdas:
factory: creates theViewwhen theAndroidViewenters the composition (again after the activity is recreated).update: runs afterfactory, and again whenever the state it reads or the values it captures change. Keep it cheap and safe to repeat.onRelease: runs when theViewis permanently discarded; remove listeners and release resources here.onReset(optional): if you pass it, theViewcan be reused, for example inside a lazy list. It runs when theViewis about to be reused, so you reset its state.
| Bridge | Direction | Key API | Lifecycle concern |
|---|---|---|---|
ComposeView | Views → Compose | setContent, viewCompositionStrategy | Must dispose when the view is gone |
AndroidView | Compose → Views | factory, update, onRelease, onReset | update can run often; onRelease must clean up |
Strategy choice
The default is DisposeOnDetachedFromWindowOrReleasedFromPool: dispose when the view is detached from the window, unless it is inside a pooling container such as a RecyclerView, where it waits until the view is released from the pool. DisposeOnViewTreeLifecycleDestroyed disposes when the view's ViewTreeLifecycleOwner is destroyed; in a Fragment that is the fragment's view lifecycle (onDestroyView), which is why the docs recommend it for Fragments. DisposeOnLifecycleDestroyed(owner) ties disposal to a LifecycleOwner you pass, such as viewLifecycleOwner.
Incremental migration
Add a ComposeView to a screen. Replace one section at a time. Keep legacy parts (a RecyclerView, a MapView) inside AndroidView. Ship each section behind a flag. This lets a team move from XML to Compose without a big-bang rewrite.
Notes
ComposeViewis aViewsubclass. Without an explicit strategy it usesDisposeOnDetachedFromWindowOrReleasedFromPool, so it does dispose; the question is whether that is the right moment.DisposeOnViewTreeLifecycleDestroyedis the recommended strategy for aComposeViewin aFragment: it disposes when the fragment's view lifecycle is destroyed, so composition state survives a temporary detach but notonDestroyView.DisposeOnLifecycleDestroyed(owner)disposes when the givenLifecycleOwneris destroyed. Passing a longer-lived owner (the activity, a parent fragment) keeps compositions alive after their views are gone.- Set the strategy before
setContentso it applies from the first composition. AndroidView'sfactoryruns when the node enters composition. It is the place to create (or inflate) theViewand to set things that never change.AndroidView'supdateruns afterfactoryand again when the state it reads changes. Put changing values there, keep it cheap, and make it safe to call repeatedly.onReleaseruns when theViewis discarded; remove listeners, stop players, and detach an adapter that outlives the view.onResetonly matters for reuse in lazy layouts, and passing it opts theViewinto reuse.- Incremental migration: add a
ComposeViewto a screen, replace sections one at a time, keep legacy parts inAndroidView, and gate each swap behind a feature flag. - Compose measures an
AndroidViewby converting its constraints toMeasureSpecs. Compose tests cannot see inside the embeddedView(use Espresso there), and everyAndroidViewadds a realViewto the hierarchy, so do not use one per row of a big lazy list without reuse. - To embed an existing XML layout,
AndroidViewBinding(fromui-viewbinding) inflates it through its ViewBinding class. To embed a whole Fragment,AndroidFragment(fromfragment-compose) exists.
Code example
This Fragment hosts a Compose tree via ComposeView (Views → Compose) and, inside that tree, embeds a legacy RecyclerView via AndroidView (Compose → Views). It shows the correct strategy, the three-lambda pattern, and the cleanup that prevents a leak.
// Views → Compose: Fragment hosts a Compose tree
class InteropFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val cv = ComposeView(requireContext())
// Safe for Fragments: disposes when the view leaves the tree
cv.viewCompositionStrategy =
ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed
cv.setContent { InteropScreen() }
return cv
}
}
// Compose → Views: embed a legacy RecyclerView
@Composable
fun InteropScreen() {
val adapter = remember { LegacyAdapter() }
Column {
Text("New Compose section")
AndroidView(
factory = { ctx ->
val rv = RecyclerView(ctx)
rv.layoutManager = LinearLayoutManager(ctx)
rv.adapter = adapter
rv
},
modifier = Modifier.weight(1f),
update = { rv -> /* set values that change with state here */ },
onRelease = { rv -> rv.adapter = null } // detach adapter
)
}
}
// Minimal stub; in production this is your existing adapter
class LegacyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = View(parent.context)
return object : RecyclerView.ViewHolder(view) {}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {}
override fun getItemCount(): Int = 0
}DisposeOnViewTreeLifecycleDestroyedis the recommended strategy for aComposeViewcreated in aFragment; it disposes when the fragment's view lifecycle is destroyed.factorycreates theRecyclerViewand sets the layout manager and adapter once. Do not reassign the adapter inupdate:setAdapterdrops and recycles every visible view even when it is the same adapter.onReleasesetsadapter = null, which unregisters the RecyclerView's observer from the adapter. This matters when the adapter lives longer than the view (for example it is held by the Fragment); otherwise the adapter keeps the old view alive.remember { LegacyAdapter() }ensures the adapter is created once and survives recompositions ofInteropScreen.
Run the idea in plain Kotlin
class LegacyView(val name: String) {
var text: String = ""
var released: Boolean = false
fun release() { released = true }
}
class ComposeNode {
var view: LegacyView? = null
var updateCount: Int = 0
fun factory(): LegacyView {
val v = LegacyView("embedded")
view = v
return v
}
fun update(v: LegacyView, newText: String) {
v.text = newText
updateCount++
}
fun onRelease(v: LegacyView) {
v.release()
view = null
}
}
fun main() {
val node = ComposeNode()
val v = node.factory()
println("Created: " + v.name)
node.update(v, "hello")
node.update(v, "world")
println("Text after 2 updates: " + v.text + " (count=" + node.updateCount + ")")
node.onRelease(v)
println("Released: " + v.released + ", node.view=" + node.view)
}Expected output:
Created: embedded
Text after 2 updates: world (count=2)
Released: true, node.view=null
In production
- Users on low-RAM devices saw the app crash with OutOfMemoryError after swiping through many pages in a
ViewPager2. - Each page was a
Fragmentthat created aComposeViewwithDisposeOnLifecycleDestroyed(parentFragment). - Because all pages shared the parent fragment's lifecycle, old compositions were never disposed when pages were off-screen.
- Reproduced by swiping through many pages and watching heap growth in the Memory Profiler; compositions and page views from old pages stayed retained.
- Changed the strategy to
DisposeOnViewTreeLifecycleDestroyedso each page's composition is disposed when that page fragment's view is destroyed. - Added a LeakCanary check in CI that navigates through many pages and fails on any retained page views.
- A player screen embedded a legacy
RecyclerViewof tracks viaAndroidView. Itsupdateblock readuiState, which also held the playback position. - The position updated many times per second, so
updatere-ran each time and calledadapter.notifyDataSetChanged(), rebinding every visible row. - Frame times spiked on mid-range devices and users reported stuttering while music played.
- Confirmed with a system trace that
onBindViewHolderran for every row on each position tick. - Switched the adapter to
ListAdapterand madeupdateread only the track list:update = { rv -> adapter.submitList(tracks) }.submitListwith the same list instance does nothing, and a new list is diffed off the main thread. - Moved the playback position into the Compose part of the screen (the player bar), so the list no longer depends on it.
- Verified in a new trace that rows are bound only when the track list changes.
Common mistakes
- Using DisposeOnLifecycleDestroyed with the wrong owner. If you pass the parent fragment or activity instead of the fragment's
viewLifecycleOwner, the composition outlives the view and leaks. UseDisposeOnViewTreeLifecycleDestroyedforFragment-scopedComposeViews. - Heavy or non-idempotent work in AndroidView update.
updatere-runs whenever the state it reads changes. CallingnotifyDataSetChanged(), reassigning the adapter or starting work there causes jank. Read only the state theViewneeds and use cheap, repeat-safe calls such assubmitList. - Not cleaning up in onRelease. Listeners registered on long-lived objects, players, and an adapter held by a Fragment keep the old
Viewalive after theAndroidViewleaves the composition. Remove them inonRelease. - Relying on the default strategy in a Fragment. The default disposes on detach from window, which does not match the fragment's view lifecycle. Set
DisposeOnViewTreeLifecycleDestroyedbeforesetContent. - Creating the View outside factory and reusing it. A
Viewcan only have one parent. Passing aViewthat is still attached elsewhere intoAndroidViewthrowsIllegalStateException("The specified child already has a parent"). Create it insidefactory. - Setting changing values only in factory.
factoryruns once per time the node enters composition, so text or data set there never updates when state changes. Put values that depend on state inupdate.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Explain how ComposeView works and what ViewCompositionStrategy controls.”
“What is the difference between factory, update, onRelease and onReset in AndroidView?”
“How would you migrate a large XML layout screen to Compose?”
“A user reports OutOfMemoryError after navigating between screens. What do you check?”
Quiz
What does ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed do?
In AndroidView, when is the factory lambda called?
What is the correct action inside AndroidView's onRelease?
A ComposeView is created in a Fragment's onCreateView. Which ViewCompositionStrategy makes the composition follow the fragment's view lifecycle?
0 of 4 answered
Mini task
Embed a legacy View in Compose and verify no leak (15 min)
- Open a
Fragmentthat currently inflates an XML layout containing aRecyclerView. - Replace the
onCreateViewbody with aComposeViewusingViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed. - Inside
setContent, add aText("Hello from Compose")and anAndroidViewthat creates the sameRecyclerViewwith aLinearLayoutManager. - In
factory, create theRecyclerView, set the layout manager and the adapter. In theupdateblock, submit the current list. In theonReleaseblock, setadapter = null. - Add LeakCanary as a debug dependency. Run the app, navigate to the screen, scroll the list, then press Back. Open Logcat and filter for
LeakCanary.
Done condition: The screen shows the Text above a working RecyclerView. Pressing Back shows no LeakCanary warning. The RecyclerView still scrolls and recycles items correctly.