DEV Community

Cover image for Living on the Seam: Running Compose and Views Side by Side Without the Pain
Android Expert
Android Expert

Posted on Originally published at Medium

Living on the Seam: Running Compose and Views Side by Side Without the Pain

Nobody rewrites a production Android app in one sprint. What actually ships is a shipment-details screen with a legacy header view, a Compose timeline, a third-party map that will never be rewritten, and a RecyclerView whose rows are being converted one at a time. That mixed state can last for years, and it is the state where most migration bugs live.

This post is a field guide to the seam between the two UI runtimes. It covers the lifecycle owners that must cross it, the state and theme that must stay consistent across it, and the failure modes that show up when they don’t.

the-seam

What you’ll take away

  • Choose ViewCompositionStrategy deliberately, because it decides which clock owns your composition.
  • Treat AndroidView's factory and update as two different contracts, not two places to put code.
  • Keep one source of truth for state and theme, and test that the two renderers agree.
  • Hand over the back stack once instead of letting two navigators coexist.
  • Compose once per ViewHolder, never once per bind.
  • Test the seam itself, not only each side of it.

1. Compose inside Views: ComposeView and ViewCompositionStrategy

The minimal host

A ComposeView is an ordinary View that owns a composition. You can declare it in XML next to legacy views, or create it in code. Because every Fragment that hosts Compose needs the same strategy decision, centralize it once:

/** The only place in the codebase that picks a strategy for Fragment-hosted Compose. */
fun Fragment.composeRoot(
    @IdRes viewId: Int,
    content: @Composable () -> Unit,
): ComposeView = ComposeView(requireContext()).apply {
    id = viewId
    setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
    setContent(content)
}
Enter fullscreen mode Exit fullscreen mode
class ShipmentDetailFragment : Fragment() {

    private val viewModel: ShipmentViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View = composeRoot(R.id.shipment_compose_root) {
        ParcelTheme {
            val state by viewModel.state.collectAsStateWithLifecycle()
            ShipmentScreen(state = state, onAction = viewModel::onAction)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Calling composeRoot from onCreateView is safe even though collectAsStateWithLifecycle() reads LocalLifecycleOwner. setContent doesn't compose anything yet. Composition starts when the view attaches to a window, and by then the Fragment has published viewLifecycleOwner on the view tree. That is also why the strategy looks the owner up at attach time rather than at construction time. If you create the ComposeView somewhere that is not under a Fragment or Activity, there is no owner to find, which is the trap covered below.

For a screen that is genuinely half legacy, put the ComposeView in the layout and configure it in onViewCreated:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.parceltrail.ui.LegacyHeaderView
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/timeline"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>
Enter fullscreen mode Exit fullscreen mode
class MixedShipmentFragment : Fragment(R.layout.fragment_shipment_mixed) {

    private var _binding: FragmentShipmentMixedBinding? = null
    private val binding get() = _binding!!

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentShipmentMixedBinding.bind(view)
        binding.timeline.apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent { ParcelTheme { TimelineSection() } }
        }
    }

    override fun onDestroyView() {
        _binding = null   // never keep the view hierarchy alive past its lifecycle
        super.onDestroyView()
    }
}
Enter fullscreen mode Exit fullscreen mode

Two clocks, one composition

A composition must be disposed at some point, and something has to decide when. That something is the ViewCompositionStrategy. Two different clocks are available. One is window attachment: is the view attached to a window right now? The other is a lifecycle: has the owner of this view reached DESTROYED? In a Compose-only app they nearly coincide. In a Fragment-based app they don't, and that gap is the source of most of the bugs below.

composition-lifetime

The default is DisposeOnDetachedFromWindowOrReleasedFromPool. Outside a pooling container it disposes when the view detaches from the window. Inside one, such as a RecyclerView, it waits until the container detaches or the item is discarded. Google's interop guide notes that when Compose is added incrementally, this default can lose state in some scenarios, which is exactly why you pick explicitly.

Why Fragments want DisposeOnViewTreeLifecycleDestroyed

A Fragment’s view has its own lifecycle, exposed as viewLifecycleOwner, and the Fragment machinery publishes it on the view tree. DisposeOnViewTreeLifecycleDestroyed looks up that owner when the view attaches and disposes the composition when the lifecycle reaches DESTROYED. The composition's lifetime now matches the Fragment view's lifetime exactly, instead of whatever the window happens to be doing.

Typical failure modes when you leave the window-based default in a Fragment:

  • Disposal while the Fragment view is still alive. Anything that detaches the view from the window mid-life, such as a parent that temporarily removes children or a transition that reparents the view, disposes the composition. When the view re-attaches you get a brand-new composition: remember state is gone and effects restart. This is the "state loss in some scenarios" the official guide warns about.
  • Effects that outlive their purpose. The opposite mismatch also exists. If composition lifetime is not tied to the Fragment view, a LaunchedEffect collecting a flow may keep running after you consider the screen gone. Tie the clock to the owner you actually mean.
  • A retained binding. Holding _binding after onDestroyView keeps the whole hierarchy, including the ComposeView, reachable. Null it out, as in the example above.
  • Duplicate IDs. If a layout contains several ComposeViews, each needs a unique id for saved state to work. Define them in res/values/ids.xml and set them explicitly when you create views in code.

The ViewTreeOwner traps

Compose doesn’t talk to Activities or Fragments directly. It reads three owners from the view tree:

  • ViewTreeLifecycleOwner drives effects, collectAsStateWithLifecycle, and the recomposer's frame clock.
  • ViewTreeSavedStateRegistryOwner backs rememberSaveable.
  • ViewTreeViewModelStoreOwner is what viewModel() resolves against.

Inside an Activity or Fragment hierarchy these are installed for you. Outside one, they aren’t. A plain android.app.Dialog, a PopupWindow, or a view added through WindowManager from a Service has its own window root, and that root has no owners. Compose then fails on first attach with an IllegalStateException complaining that no ViewTreeLifecycleOwner (or ViewTreeSavedStateRegistryOwner) was found on the view.

When the dialog should live and die with its host screen, borrow the host’s owners:

fun Dialog.borrowViewTreeOwners(from: View) {
    val decor = checkNotNull(window).decorView
    decor.setViewTreeLifecycleOwner(from.findViewTreeLifecycleOwner())
    decor.setViewTreeSavedStateRegistryOwner(from.findViewTreeSavedStateRegistryOwner())
    decor.setViewTreeViewModelStoreOwner(from.findViewTreeViewModelStoreOwner())
}

// usage inside a Fragment
Dialog(requireContext()).apply {
    borrowViewTreeOwners(requireView())
    setContentView(ComposeView(context).apply { setContent { ParcelTheme { ScanHelpSheet() } } })
    show()
}
Enter fullscreen mode Exit fullscreen mode

Three details matter here:

  1. Install the owners on the root of the window, which is the decor view for a dialog and the view you pass to WindowManager.addView for an overlay. Setting them on a deeper child is too late for the recomposer lookup.
  2. Borrowed owners mean borrowed lifetime. Dismiss the dialog when the host view’s lifecycle ends, or it will outlive the owner it points at.
  3. A Service-hosted overlay has no host to borrow from. You must supply your own LifecycleOwner, SavedStateRegistryOwner and ViewModelStoreOwner, and move that lifecycle to at least STARTED. In the Compose runtime's window recomposer, the composition frame clock is created paused, resumes on ON_START and pauses again on ON_STOP. Frame-driven work such as applying recompositions and running animations therefore stops while the owner sits below STARTED, and a screen that renders once and then looks frozen is the typical symptom of an owner stuck at CREATED.

Where you can, prefer a dialog type that installs the owners for you, such as androidx ComponentDialog, or avoid a framework dialog entirely and use Compose's own Dialog composable from inside a composition.

2. Views inside Compose: AndroidView with factory and update

The reverse direction is for things you can’t or won’t rewrite yet: a map SDK, an ad view, a custom-drawn gauge with ten years of tuning in it. AndroidView takes a factory and an update, and the whole API follows from one rule: they are different contracts.

androidview-lifecycle

  • factory runs once, on the UI thread, to create the View. It's the place for constants and for listeners that push events from the View into Compose.
  • update runs once right after factory, then again whenever state it reads changes (or its captured inputs do). It pushes Compose state into the View.
  • onReset runs when a view is about to be reused, for example by a lazy list. Without a non-null onReset, views are discarded and recreated when the node moves or is removed instead of being reused.
  • onRelease runs when the view leaves the composition permanently, and Compose never reuses that instance afterwards.

Wrapping a legacy map view

Here is ParcelTrail’s RouteMapView, a View-based map with its own tile loading that must follow the host lifecycle. The Compose wrapper stays thin:

@Composable
fun RouteMap(
    stops: List<StopUi>,
    selectedStopId: String?,
    onStopTapped: (String) -> Unit,
    modifier: Modifier = Modifier,
) {
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    val currentOnStopTapped by rememberUpdatedState(onStopTapped)
    val accent = MaterialTheme.colorScheme.primary.toArgb()

    AndroidView(
        modifier = modifier.testTag("route_map"),
        factory = { context ->
            RouteMapView(context).apply {
                setOnStopTappedListener { id -> currentOnStopTapped(id) }
            }
        },
        update = { map ->
            map.bindLifecycle(lifecycle)   // idempotent: a no-op unless the owner actually changed
            map.setAccentColor(accent)
            if (map.renderedStops != stops) map.showRoute(stops)
            if (map.highlightedStopId != selectedStopId) map.highlight(selectedStopId)
        },
        onRelease = { map -> map.release() },
    )
}
Enter fullscreen mode Exit fullscreen mode

The lifecycle is bound in update, not factory, so a changed LocalLifecycleOwner is picked up instead of being frozen at first composition. The side effect lives in the View, which makes it idempotent and lets onRelease remove the observer deterministically. Reading LocalLifecycleOwner.current in the composable body is fine, but the observer registration must never happen there, since the body can run many times. The View side owns its lifecycle bookkeeping, so the wrapper never has to:

class RouteMapView(context: Context) : FrameLayout(context), DefaultLifecycleObserver {

    var renderedStops: List<StopUi> = emptyList(); private set
    var highlightedStopId: String? = null; private set
    private var boundLifecycle: Lifecycle? = null

    fun bindLifecycle(lifecycle: Lifecycle) {
        if (boundLifecycle === lifecycle) return          // same owner: nothing to do
        boundLifecycle?.removeObserver(this)              // owner changed: move the observer
        boundLifecycle = lifecycle.also { it.addObserver(this) }
    }

    override fun onStart(owner: LifecycleOwner) = resumeTileLoading()
    override fun onStop(owner: LifecycleOwner) = pauseTileLoading()

    fun release() {
        boundLifecycle?.removeObserver(this)
        boundLifecycle = null
        freeNativeHandles()
    }

    // showRoute(), highlight(), setAccentColor(), tile loading elided
}
Enter fullscreen mode Exit fullscreen mode

Failure modes worth designing against

Stale lambdas. The factory lambda captures onStopTapped once. If the caller passes a new lambda on a later recomposition, the listener installed in factory still points at the old one. rememberUpdatedState (as above) fixes this without re-registering the listener on every pass.

Unconditional work in update. update is a hot path. Calling setText, setAdapter or showRoute unconditionally redoes work on every pass and often triggers layout. Diff first, as in the map example. The classic example is a text field wrapped from the View world, where unguarded writes create a feedback loop and a jumping caret:

AndroidView(
    factory = { ctx ->
        AppCompatEditText(ctx).apply {
            doAfterTextChanged { editable -> currentOnChange(editable?.toString().orEmpty()) }
        }
    },
    update = { edit ->
        if (edit.text?.toString() != value) {   // break the loop, preserve the caret
            edit.setText(value)
            edit.setSelection(edit.text?.length ?: 0)
        }
    },
)
Enter fullscreen mode Exit fullscreen mode

If you find yourself writing that, check first whether Compose’s own TextField can do the job. AndroidView is for components that lack a Compose equivalent, not for ones you haven't gotten around to rewriting.

Holding the View outside factory. Creating the view with remember outside AndroidView and returning it from factory makes its lifetime unclear. Build it inside factory and clean it up in onRelease.

Reuse without onReset. In a LazyColumn, a wrapped view that has no onReset is thrown away and rebuilt as items scroll. If you do supply one, make it clear transient state, so a recycled view never flashes the previous item's content.

Surface-backed views. Views that render to their own surface, such as many map and video components, don’t always take part in Compose’s alpha, rotation and clipping the way ordinary views do. Expect visual glitches when you animate them or put them in rounded containers, and test those cases early.

Opaque to semantics. Compose tests can’t see inside an AndroidView. Give it a testTag (as above) and test the inner content with Espresso. Section 6 covers this.

For larger legacy chunks, AndroidViewBinding (from androidx.compose.ui:ui-viewbinding) inflates an XML layout inside Compose. Google's guidance is to use it for smaller legacy layouts during an incremental migration, not as a way to host a full-screen XML layout in a Compose-only app.

3. Sharing state and theming across the boundary

One source of truth, two renderers

The worst interop bugs come from state that lives on both sides: a remembered value in Compose mirroring a field on a View, each updating the other. Pick a single owner, normally a ViewModel exposing StateFlow<UiState>, and let both worlds render from it. State flows down. Actions flow back up through one method.

state-and-theme-bridge

data class ShipmentUiState(
    val header: HeaderUi,
    val stops: List<StopUi>,
    val selectedStopId: String?,
)

sealed interface ShipmentAction {
    data class SelectStop(val id: String) : ShipmentAction
    data object Refresh : ShipmentAction
}

class ShipmentViewModel(private val repo: ShipmentRepository) : ViewModel() {
    private val _state = MutableStateFlow(ShipmentUiState.Loading)
    val state: StateFlow<ShipmentUiState> = _state.asStateFlow()

    fun onAction(action: ShipmentAction) { /* reduce into _state */ }
}
Enter fullscreen mode Exit fullscreen mode

The View side collects with a lifecycle-aware scope and binds only what changed:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    _binding = FragmentShipmentMixedBinding.bind(view)

    viewLifecycleOwner.lifecycleScope.launch {
        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.state
                .map { it.header }
                .distinctUntilChanged()
                .collect(binding.header::bind)
        }
    }

    binding.timeline.apply {
        setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
        setContent {
            ParcelTheme {
                val state by viewModel.state.collectAsStateWithLifecycle()
                Timeline(
                    stops = state.stops,
                    selectedStopId = state.selectedStopId,
                    onSelect = { viewModel.onAction(ShipmentAction.SelectStop(it)) },
                )
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Two rules keep this honest:

  • Composables below the entry point take state and lambdas, never the ViewModel. Only the host, whether a Fragment or a top-level route composable, touches it. This keeps previews and tests trivial and avoids reaching for viewModel() where a different owner might resolve.
  • Know which owner viewModel() resolves against. Inside a Fragment-hosted ComposeView, it resolves against the owner found on the view tree, which is the Fragment's own store. For an Activity-scoped or nav-graph-scoped ViewModel, obtain it in the Fragment (activityViewModels(), navGraphViewModels()) and pass it in. Don't guess at it from inside the composition.

Theming: the XML theme is the reference

During migration you have two theme systems, and Google’s own migration guide says so plainly: your styling now has two sources of truth, and it tells you to treat the existing XML values as the reference for the Compose theme, never inventing new values, and never hardcoding migrated ones. The simplest way to honor that is to make Compose read the very same resources:

@Composable
fun ParcelTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit,
) {
    val base = if (darkTheme) darkColorScheme() else lightColorScheme()
    val scheme = base.copy(
        primary = colorResource(R.color.parcel_primary),
        onPrimary = colorResource(R.color.parcel_on_primary),
        surface = colorResource(R.color.parcel_surface),
        onSurface = colorResource(R.color.parcel_on_surface),
    )
    MaterialTheme(colorScheme = scheme, typography = ParcelTypography, content = content)
}
Enter fullscreen mode Exit fullscreen mode

Because values-night/colors.xml already flips those resources, Compose and Views change together. A theme-adapter library that reads ?attr/ values from your XML theme is another route. If you adopt one, check that it is maintained against your Material and Compose versions. Either way, the rule is the same: one definition, read by both.

The other direction deserves attention too. A View inside AndroidView is inflated against the Activity's XML theme. It does not see MaterialTheme. If a Compose-only override should reach it, push the value through update explicitly, as setAccentColor(accent) does in the map example above. Because accent is read from composition, update re-runs when it changes.

Common ways the two renderers drift apart:

  • Dynamic color on one side only. If Compose uses a dynamic color scheme but the XML theme never opts in, the screen shows two palettes. Make that decision once.
  • Casting LocalContext.current to Activity. The context is often a ContextWrapper, and the cast throws. Unwrap it:
  tailrec fun Context.findActivity(): Activity? = when (this) {
      is Activity -> this
      is ContextWrapper -> baseContext.findActivity()
      else -> null
  }
Enter fullscreen mode Exit fullscreen mode
  • Hardcoded values “just for now”. They survive. Add a parity test (section 6) so drift fails a build instead of a design review.

4. Navigation strategy during migration

Navigation is where gradual migration is least gradual. Google’s navigation migration guide is explicit about the constraint: you can’t mix Fragment destinations and composable destinations inside one navigation setup. The prerequisite for Navigation Compose is that every Fragment destination has been replaced by a screen composable. Until then, keep the Fragment-based Navigation component. Composables may still contain View content through AndroidView, but the destinations themselves must all be composables.

There are two supported ways to cross that line, and both go through a wrapper. A Fragment destination can host Compose through a ComposeView, and a composable destination can host a Fragment through AndroidFragment. What you can't do is declare Fragment and composable destinations side by side in one graph and let a single navigator own both. That turns navigation into a hand-over, not a blend.

navigation-phases

Phase 1: the Fragment shell

NavHostFragment and the XML graph stay in charge. Compose screens live inside Fragments, and they request navigation through callbacks. They never receive a NavController.

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
): View {
    val nav = findNavController()
    return composeRoot(R.id.parcel_list_compose_root) {
        ParcelTheme {
            ParcelListRoute(
                onOpenShipment = { id ->
                    nav.navigate(ParcelListFragmentDirections.actionToShipment(id))
                },
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Keeping navigation out of the composables pays off twice. It keeps them previewable, and it makes Phase 3 a mechanical change, because only the lambdas’ bodies change.

Phase 2: Compose-heavy, still Fragment-owned

Most destinations are Compose by now. The Fragments are thin wrappers, and shared ViewModels are scoped the way they will be later. Use this phase to define route types as plain serializable classes and to migrate the last stragglers. Don't start a second NavController here; two back stacks describing one screen is the migration's most expensive failure mode.

Phase 3: the Compose shell

Once every destination is a composable, flip the whole graph in one release, behind a flag if you need a rollback:

@Serializable data object ParcelList
@Serializable data class ShipmentDetail(val shipmentId: String)
@Serializable data object Scanner

@Composable
fun ParcelTrailNavHost(navController: NavHostController = rememberNavController()) {
    NavHost(navController = navController, startDestination = ParcelList) {
        composable<ParcelList> {
            ParcelListRoute(onOpenShipment = { navController.navigate(ShipmentDetail(it)) })
        }
        composable<ShipmentDetail> { entry ->
            ShipmentRoute(shipmentId = entry.toRoute<ShipmentDetail>().shipmentId)
        }
        composable<Scanner> {
            // A legacy screen that still has to be a Fragment, wrapped as a composable destination
            AndroidFragment<ScannerFragment>(modifier = Modifier.fillMaxSize())
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

AndroidFragment (from androidx.fragment:fragment-compose) is a transitional tool. It lets a single stubborn Fragment ride inside an otherwise-Compose graph, which is compatible with the all-composable-destinations rule because the destination itself is a composable. Google's interop docs also note that from Fragment 1.9.0 you can cap an embedded fragment's maximum lifecycle, for example keeping off-screen pager pages at STARTED while the settled page is RESUMED. The exact AndroidFragment parameters have varied between releases, so check the Fragment release notes for your version before relying on it. For Compose-only apps, the same docs recommend a single Activity with Navigation 3 as the end state. Route types that are plain serializable classes keep that option open.

Guard rails that apply in every phase

  • Back handling. A Fragment’s OnBackPressedCallback and a Compose BackHandler register on the same Activity dispatcher, and the most recently registered enabled callback gets the first chance. If back "does nothing" or does the wrong thing, check who registered last and who is still enabled. Predictive back also needs the app to opt in.
  • Shared ViewModel scoping at the flip. A Fragment graph scopes with navGraphViewModels. After the flip, scope to the nav back stack entry instead:
  composable<ShipmentDetail> { entry ->
      val parentEntry = remember(entry) { navController.getBackStackEntry<CheckoutGraph>() }
      val checkoutViewModel: CheckoutViewModel = viewModel(parentEntry)
      // ...
  }
Enter fullscreen mode Exit fullscreen mode

Verify that the two scopes have the same lifetime before shipping. A ViewModel that used to survive a screen and now doesn't is a silent behavior change.

  • Deep links. Keep one router. Two graphs both claiming the same URI is a bug that only reproduces from a notification.
  • Arguments. Pass identifiers, not objects, and load the data in the ViewModel. Saved state and process death will thank you.

5. Performance: Compose in RecyclerView items

Strategy for pooled views

RecyclerView recycles views through a pool, and the default strategy is built for that. When the ComposeView sits in a pooling container, composition is disposed when the container detaches or the item is discarded, not on every transient detach as the row scrolls off and back on. That is the behavior you want, so leave it alone.

DisposeOnViewTreeLifecycleDestroyed is the wrong override here. It ties each row's composition to the host Fragment's view lifetime. Nothing disposes a row's composition when its holder is pooled or dropped, so compositions can stay reachable through the recomposer, with their effects still active, until the whole Fragment view dies. In a long list that adds up.

One caveat: pooling-aware disposal depends on RecyclerView’s pooling-container support, which arrived in the 1.3 line. If you’re pinned to an older RecyclerView, the default degrades to plain detach-based disposal. Upgrade, or check the release notes before relying on it.

Compose once per ViewHolder, then push state

The expensive mistake is calling setContent inside onBindViewHolder. Every bind creates a new composition.

recyclerview-compose-row

class ParcelRowHolder(private val composeView: ComposeView) : RecyclerView.ViewHolder(composeView) {

    private var row by mutableStateOf<ParcelRow?>(null)

    init {
        // This is already the default; stating it makes the intent reviewable.
        composeView.setViewCompositionStrategy(
            ViewCompositionStrategy.DisposeOnDetachedFromWindowOrReleasedFromPool,
        )
        composeView.setContent {
            ParcelTheme { row?.let { ParcelRowContent(it) } }
        }
    }

    fun bind(model: ParcelRow) {
        row = model          // a snapshot state write: recomposes this row only
    }
}

class ParcelAdapter : ListAdapter<ParcelRow, ParcelRowHolder>(ParcelRowDiff) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ParcelRowHolder(
            ComposeView(parent.context).apply {
                layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
            },
        )

    override fun onBindViewHolder(holder: ParcelRowHolder, position: Int) =
        holder.bind(getItem(position))
}
Enter fullscreen mode Exit fullscreen mode

Keep rows cheap and stable

  • Stable models. Mark row models @Immutable (or keep them to stable types such as String, Int and immutable collections) so unchanged rows can skip recomposition. Recent Compose compiler versions enable strong skipping by default, which relaxes this, but stable models still make your intent explicit.
  • Give each ComposeView a unique id when a layout contains several, as in section 1.
  • No scrollables with unbounded height. A LazyColumn inside a wrap_content row throws an IllegalStateException about a vertically scrollable component measured with infinite maximum height. Rows should not scroll.
  • Nested scroll interop. For a Compose scrollable inside a View-based scrolling parent such as a CoordinatorLayout, connect the two with Modifier.nestedScroll(rememberNestedScrollInteropConnection()), or fling and collapse behavior will feel broken.
  • Expect first-appearance cost, and confirm it in a trace. A row type’s first composition is more expensive than later binds. Profile with a system trace rather than assuming that RecyclerView prefetching hides it, and make sure your baseline profile covers the row composables.
  • If most of the list is Compose, stop using RecyclerView. A LazyColumn has no interop tax. The ComposeView-per-row pattern is a bridge for lists that are still mostly Views.

Measure instead of guessing. A Macrobenchmark with FrameTimingMetric gives you a before/after you can defend:

@get:Rule val benchmarkRule = MacrobenchmarkRule()

@Test
fun scrollParcelList() = benchmarkRule.measureRepeated(
    packageName = "com.parceltrail.app",
    metrics = listOf(FrameTimingMetric()),
    iterations = 8,
    startupMode = StartupMode.WARM,
    compilationMode = CompilationMode.Partial(),
) {
    pressHome()
    startActivityAndWait()
    device.findObject(By.res("com.parceltrail.app", "parcel_list")).apply {
        setGestureMargin(device.displayWidth / 5)
        repeat(3) { fling(Direction.DOWN) }
    }
}
Enter fullscreen mode Exit fullscreen mode

Run it on a physical device against a release-like build type, and compare the frame-time distribution before and after you convert a row.

6. Testing mixed screens

A mixed screen has failure modes that neither a pure Espresso test nor a pure Compose test can see: composition disposed at the wrong time, owners missing, a theme drifting, a View reacting to state it should never have received. Spread the effort across layers and spend device time only where the seam is.

testing-layers

Test the screen through both runtimes

createEmptyComposeRule() is the rule to use when something else, such as FragmentScenario, launches the Activity. It synchronizes with Espresso, so Compose assertions and onView calls can sit in the same test:

@RunWith(AndroidJUnit4::class)
class ShipmentDetailFragmentTest {

    @get:Rule val compose = createEmptyComposeRule()

    @Test
    fun headerViewAndComposeTimelineAgree() {
        launchFragmentInContainer<ShipmentDetailFragment>(
            fragmentArgs = bundleOf("shipmentId" to "PT-1042"),
            themeResId = R.style.Theme_ParcelTrail,   // required: see below
        )

        compose.onNodeWithText("Out for delivery").assertIsDisplayed()             // Compose side
        onView(withId(R.id.header_status)).check(matches(withText("Arriving today"))) // View side
    }
}
Enter fullscreen mode Exit fullscreen mode

FragmentScenario hosts the fragment in an empty Activity, and without an explicit themeResId your app theme isn't applied. The usual symptoms are crashes about needing an AppCompat or Material theme, or Views that render un-themed. It needs fragment-testing as an androidTestImplementation dependency, and fragment-testing-manifest for the empty activity.

Reach into an AndroidView

An AndroidView hosts a real View, so Espresso can find it, while Compose can only see the node you tagged:

@get:Rule val compose = createAndroidComposeRule<HostActivity>()   // HostActivity uses the app theme

@Test
fun tappingMapStopSelectsItInTheTimeline() {
    compose.onNodeWithTag("route_map").assertIsDisplayed()

    onView(isAssignableFrom(RouteMapView::class.java)).perform(tapStop("stop-3"))

    compose.onNodeWithText("Stop 3 selected").assertIsDisplayed()
}
Enter fullscreen mode Exit fullscreen mode

Use your own host activity for these tests. The default test activity that Compose’s test manifest provides doesn’t carry your theme, so any Views inside AndroidView would render un-themed. If images load asynchronously, register an idling resource or use compose.waitUntil. Neither framework knows about your image loader.

Pin the lifecycle contract

The disposal behavior from section 1 is a contract worth protecting, and you can test it without any production code. Put a probe in a test-only Fragment that uses the same composeRoot helper, push another Fragment on the back stack so the first one's view is destroyed, and assert the composition went away:

class ProbeFragment : Fragment() {      // keep the no-arg constructor: the framework re-instantiates Fragments
    override fun onCreateView(i: LayoutInflater, c: ViewGroup?, s: Bundle?): View =
        composeRoot(R.id.probe_root) {
            DisposableEffect(Unit) { onDispose { disposed.set(true) } }
        }

    companion object {
        val disposed = AtomicBoolean(false)   // test-only signal; reset it in each test
    }
}

@Test
fun compositionIsDisposedWhenFragmentViewIsDestroyed() {
    val disposed = ProbeFragment.disposed.apply { set(false) }
    val scenario = ActivityScenario.launch(HostActivity::class.java)

    scenario.onActivity { activity ->
        activity.supportFragmentManager.commit {
            replace(android.R.id.content, ProbeFragment())
        }
    }
    InstrumentationRegistry.getInstrumentation().waitForIdleSync()
    assertFalse(disposed.get())

    scenario.onActivity { activity ->
        activity.supportFragmentManager.commit {
            replace(android.R.id.content, Fragment())
            addToBackStack(null)
        }
    }
    InstrumentationRegistry.getInstrumentation().waitForIdleSync()
    assertTrue(disposed.get())
}
Enter fullscreen mode Exit fullscreen mode

If someone later “simplifies” the helper and switches the strategy, this test fails before a user ever sees lost state.

Add a theme parity test

If Compose and XML are meant to agree, prove it:

@Test
fun composePrimaryMatchesXmlPrimary() {
    val themed = ContextThemeWrapper(targetContext, R.style.Theme_ParcelTrail)
    val xmlPrimary = MaterialColors.getColor(themed, com.google.android.material.R.attr.colorPrimary, Color.MAGENTA)

    var composePrimary = 0
    compose.setContent { ParcelTheme { composePrimary = MaterialTheme.colorScheme.primary.toArgb() } }
    compose.waitForIdle()

    assertEquals(xmlPrimary, composePrimary)
}
Enter fullscreen mode Exit fullscreen mode

Add one assertion per role you actually use, and run it in both light and dark configurations.

What to push down

Everything the ViewModel and reducers decide belongs in JVM unit tests, which are the cheapest layer. Component tests with createComposeRule and screenshot diffs cover individual composables and theme drift. Keep the interop layer small and focused on the seam, covering owners, disposal and the View/Compose hand-off. Reserve Macrobenchmarks and end-to-end runs for jank, startup and navigation hand-offs.

Preflight checklist

Before you merge a screen that mixes the two runtimes:

  • Every Fragment-hosted ComposeView goes through one helper that sets DisposeOnViewTreeLifecycleDestroyed.
  • ComposeViews in a layout have unique ids, and _binding is cleared in onDestroyView.
  • Any dialog, popup or overlay with Compose installs view-tree owners on its window root.
  • AndroidView has a cheap, diff-guarded update, rememberUpdatedState for listeners, and onRelease for cleanup.
  • State has exactly one owner, composables below the entry point take state and lambdas, and the XML theme is the reference for Compose.
  • Navigation has a single owner per phase, and composables request navigation through lambdas.
  • RecyclerView rows call setContent once per ViewHolder, with stable models and the pooling-aware strategy.
  • The seam has tests: a Fragment-scenario test, a disposal test and a theme parity test.

🔚 Closing thought

Interop isn’t hard because the two runtimes are incompatible. It’s hard because each side has its own idea of when things start and stop, and the bugs appear in the gaps between those ideas. Name the owner of every lifetime, every piece of state and every colour, and the seam gets boring. In a migration, boring is the goal.

Further reading

📱 Crack Your Next Android Interview

If you’re targeting a senior Android role at a FAANG or top-tier MNC, syntax knowledge alone won’t get you through the loop. I highly recommend “Cracking Top MNC Android Interviews” — a senior-level playbook covering framework internals, Jetpack Compose, coroutines, Android-specific system design, and DSA reframed around real mobile constraints, to help you walk into bar-raiser rounds ready.


Originally published on Medium.

Top comments (0)