Interop: Compose in Views and Views in Compose

Learn Compose and View interop in Android: host Compose with ComposeView, embed Views with AndroidView, and pick the right ViewCompositionStrategy. About 25 minutes.

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 update block 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.
  • ComposeView is a new room built inside the old house (the View tree).
  • AndroidView is an old appliance (a legacy View) plugged into the new room (a Compose layout).
  • factory is the electrician who installs the appliance once.
  • update is the daily check that the appliance is still connected and set correctly.
  • onRelease is 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 the View when the AndroidView enters the composition (again after the activity is recreated).
  • update: runs after factory, and again whenever the state it reads or the values it captures change. Keep it cheap and safe to repeat.
  • onRelease: runs when the View is permanently discarded; remove listeners and release resources here.
  • onReset (optional): if you pass it, the View can be reused, for example inside a lazy list. It runs when the View is about to be reused, so you reset its state.
BridgeDirectionKey APILifecycle concern
ComposeViewViews → ComposesetContent, viewCompositionStrategyMust dispose when the view is gone
AndroidViewCompose → Viewsfactory, update, onRelease, onResetupdate 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

  • ComposeView is a View subclass. Without an explicit strategy it uses DisposeOnDetachedFromWindowOrReleasedFromPool, so it does dispose; the question is whether that is the right moment.
  • DisposeOnViewTreeLifecycleDestroyed is the recommended strategy for a ComposeView in a Fragment: it disposes when the fragment's view lifecycle is destroyed, so composition state survives a temporary detach but not onDestroyView.
  • DisposeOnLifecycleDestroyed(owner) disposes when the given LifecycleOwner is destroyed. Passing a longer-lived owner (the activity, a parent fragment) keeps compositions alive after their views are gone.
  • Set the strategy before setContent so it applies from the first composition.
  • AndroidView's factory runs when the node enters composition. It is the place to create (or inflate) the View and to set things that never change.
  • AndroidView's update runs after factory and again when the state it reads changes. Put changing values there, keep it cheap, and make it safe to call repeatedly.
  • onRelease runs when the View is discarded; remove listeners, stop players, and detach an adapter that outlives the view. onReset only matters for reuse in lazy layouts, and passing it opts the View into reuse.
  • Incremental migration: add a ComposeView to a screen, replace sections one at a time, keep legacy parts in AndroidView, and gate each swap behind a feature flag.
  • Compose measures an AndroidView by converting its constraints to MeasureSpecs. Compose tests cannot see inside the embedded View (use Espresso there), and every AndroidView adds a real View to the hierarchy, so do not use one per row of a big lazy list without reuse.
  • To embed an existing XML layout, AndroidViewBinding (from ui-viewbinding) inflates it through its ViewBinding class. To embed a whole Fragment, AndroidFragment (from fragment-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
}
  • DisposeOnViewTreeLifecycleDestroyed is the recommended strategy for a ComposeView created in a Fragment; it disposes when the fragment's view lifecycle is destroyed.
  • factory creates the RecyclerView and sets the layout manager and adapter once. Do not reassign the adapter in update: setAdapter drops and recycles every visible view even when it is the same adapter.
  • onRelease sets adapter = 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 of InteropScreen.

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

ComposeView leak inside a ViewPager2
  • Users on low-RAM devices saw the app crash with OutOfMemoryError after swiping through many pages in a ViewPager2.
  • Each page was a Fragment that created a ComposeView with DisposeOnLifecycleDestroyed(parentFragment).
  • Because all pages shared the parent fragment's lifecycle, old compositions were never disposed when pages were off-screen.
The fix
  • 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 DisposeOnViewTreeLifecycleDestroyed so 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.
Jank from heavy work in AndroidView update
  • A player screen embedded a legacy RecyclerView of tracks via AndroidView. Its update block read uiState, which also held the playback position.
  • The position updated many times per second, so update re-ran each time and called adapter.notifyDataSetChanged(), rebinding every visible row.
  • Frame times spiked on mid-range devices and users reported stuttering while music played.
The fix
  • Confirmed with a system trace that onBindViewHolder ran for every row on each position tick.
  • Switched the adapter to ListAdapter and made update read only the track list: update = { rv -> adapter.submitList(tracks) }. submitList with 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. Use DisposeOnViewTreeLifecycleDestroyed for Fragment-scoped ComposeViews.
  • Heavy or non-idempotent work in AndroidView update. update re-runs whenever the state it reads changes. Calling notifyDataSetChanged(), reassigning the adapter or starting work there causes jank. Read only the state the View needs and use cheap, repeat-safe calls such as submitList.
  • Not cleaning up in onRelease. Listeners registered on long-lived objects, players, and an adapter held by a Fragment keep the old View alive after the AndroidView leaves the composition. Remove them in onRelease.
  • 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 DisposeOnViewTreeLifecycleDestroyed before setContent.
  • Creating the View outside factory and reusing it. A View can only have one parent. Passing a View that is still attached elsewhere into AndroidView throws IllegalStateException ("The specified child already has a parent"). Create it inside factory.
  • Setting changing values only in factory. factory runs once per time the node enters composition, so text or data set there never updates when state changes. Put values that depend on state in update.

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)

  1. Open a Fragment that currently inflates an XML layout containing a RecyclerView.
  2. Replace the onCreateView body with a ComposeView using ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed.
  3. Inside setContent, add a Text("Hello from Compose") and an AndroidView that creates the same RecyclerView with a LinearLayoutManager.
  4. In factory, create the RecyclerView, set the layout manager and the adapter. In the update block, submit the current list. In the onRelease block, set adapter = null.
  5. 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.

Next: Coroutines basics: suspend and builders