DEV Community

Cover image for Holding the Door Open: Screen-Level Predictive Back with DeferredTransitionState
Android Expert
Android Expert

Posted on Originally published at Medium

Holding the Door Open: Screen-Level Predictive Back with DeferredTransitionState

The Android system draws a lovely preview when a user swipes back to the home screen. That part is free. The part nobody hands you is what happens inside your app, when the swipe should peel one Compose screen away to reveal the one underneath, and your code has to decide what that peel looks like, whether it is allowed to finish, and what the back stack should say afterwards.

Compose 1.12 added a purpose-built tool for exactly this: a transition state that can be held in a manually driven phase, then released into a normal animation. This post walks through that model, builds a screen host on top of it, and spends most of its time on the ways it breaks in production.

What you are actually building

A back gesture is not one animation. It is two, with a handoff in the middle.

deferred-lifecycle

While the finger is down, you are the animation clock: the screen follows the thumb, and nothing is decided. When the finger lifts, the decision is made and the transition engine takes over. The important design goal is that the second phase starts from wherever the first one left off, including velocity, so the user never sees a seam.

Before DeferredTransitionState, people approximated this with SeekableTransitionState, calling seekTo with the gesture fraction and animateTo on release. It works, but the fraction has to be mapped to a position along a fixed transition, so the gesture is bound to the exact shape of the animation that will run afterwards. The deferred model removes that coupling: during the deferred phase you manipulate properties directly, and the automatic transition only begins when you say so.

The API in one pass

DeferredTransitionState<S> lives in androidx.compose.animation.core and was added in Compose Animation 1.12. It implements TransitionState, and its job is described in the reference as holding a transition in an intermediate, manually controlled state before it proceeds to its final target. Three things matter:

  • defer(target) starts the deferred phase. The new target is stored as pendingTargetState; the transition does not run.
  • animateTo(target) ends the deferred phase and begins the automatic transition.
  • rememberDeferredTransition(state) returns a DeferredTransition<S>, a specialised transition that exposes pendingTargetState while deferred. In the 1.13 line this is its own function; before that, the same role was played by a rememberTransition overload that accepted a DeferredTransitionState.

On the rendering side, DeferredAnimatedContent and DeferredAnimatedVisibility are extension functions on DeferredTransition<S>, so you cannot call them on an arbitrary Transition. Note what is not there: DeferredAnimatedContent has no targetState parameter. The target comes from the transition itself, which means you steer it through defer and animateTo, and your content lambda simply receives the state to draw. Its mutableTransformSpec is only active for a transition created through rememberDeferredTransition, and it is where you write properties such as scale or offset while the gesture is in flight. Inside it, initialContentTransform addresses the content that is leaving and targetContentTransform the content that is arriving.

defer-vs-animateto

The mental shortcut: defer means "I am steering", animateTo means "you take it from here." Calling defer repeatedly as gesture events arrive is normal. Calling animateTo exactly once per gesture outcome is the rule you want to hold yourself to.

A state machine, not a callback

Most bugs in this area come from treating the gesture as a single event. It is a small state machine, and writing it down makes the failure cases obvious.

back-gesture-states

Every exit from Deferred is an animateTo. Commit goes to the previous screen; cancel goes back to the current one. The dashed arrow is the one that hurts: a user who starts a second swipe while the first is still settling. We will come back to it.

Pairing it with Navigation

There are two honest ways to combine this with a navigation library, and which one you pick depends on how much of the animation you want to own.

Option A: stay inside Navigation 3 and customize the predictive spec

If you only need a different look for the system-driven gesture, Navigation 3’s NavDisplay already exposes a dedicated hook. It accepts a predictivePopTransitionSpec that receives the swipe edge and returns a ContentTransform, and you can override it per entry through metadata:

entry<DetailKey>(
    metadata = NavDisplay.predictivePopTransitionSpec { _ ->
        EnterTransition.None togetherWith
            slideOutHorizontally(targetOffsetX = { it })
    },
) { key ->
    DetailScreen(key)
}
Enter fullscreen mode Exit fullscreen mode

This is the lowest-risk path. You do not manage gesture state at all; the trade-off is that you describe the result as a ContentTransform rather than driving individual properties from the thumb. It also keeps getting better without your involvement: the Navigation 3 1.3.0-alpha01 release notes say NavDisplay migrated its predictive back handling to DeferredAnimatedContent to fix handoff problems, so the deferred model is already working underneath the library.

Option B: own the host, keep the back stack as the source of truth

When the screen itself should react to the gesture (scale, parallax, a shared element that tracks the finger), build a small host around DeferredTransitionState. NavDisplay uses the deferred machinery internally, but it does not accept a DeferredTransitionState of your own or expose the swipe progress to your screens, so this host is a pattern you own, not an official integration point.

navigation-pairing

The rule that keeps this sane: the back stack changes on commit, never before. Everything prior to that is presentation.

// Needed on Compose 1.12; the opt-in was removed in 1.13.0-alpha03.
@OptIn(ExperimentalDeferredTransitionApi::class)
@Composable
fun <T : Any> DeferredBackHost(
    backStack: SnapshotStateList<T>,
    stateKey: (T) -> Any,
    modifier: Modifier = Modifier,
    screen: @Composable (T) -> Unit,
) {
    check(backStack.isNotEmpty()) { "DeferredBackHost needs at least one entry" }
    val top = backStack.last()
    val previous = backStack.getOrNull(backStack.lastIndex - 1)

    var gestureTarget by remember { mutableStateOf<T?>(null) }
    var swipeProgress by remember { mutableFloatStateOf(0f) }

    val state = remember { DeferredTransitionState(top) }
    val transition = rememberDeferredTransition(state)
    val saveable = rememberSaveableStateHolder()

    // Drive the state from an effect, not from the composition body.
    LaunchedEffect(gestureTarget, top) {
        val held = gestureTarget
        if (held != null) state.defer(held) else state.animateTo(top)
    }

    PredictiveBackHandler(enabled = previous != null) { events ->
        val destination = previous ?: return@PredictiveBackHandler
        swipeProgress = 0f                 // reset at the START of a gesture
        gestureTarget = destination
        try {
            events.collect { swipeProgress = it.progress }
            backStack.removeLastOrNull()   // flow completed: commit
        } finally {
            gestureTarget = null           // commit and cancel both release
        }
    }

    // No targetState argument: the transition's state is driven by defer/animateTo above.
    transition.DeferredAnimatedContent(
        modifier = modifier,
        mutableTransformSpec = {
            MutableContentTransform {
                initialContentTransform { scale = 1f - 0.1f * swipeProgress }
            }
        },
        transitionSpec = {
            (fadeIn() + slideInHorizontally { -it / 4 }) togetherWith
                (fadeOut() + slideOutHorizontally { it })
        },
    ) { entry ->
        saveable.SaveableStateProvider(stateKey(entry)) { screen(entry) }
    }
}
Enter fullscreen mode Exit fullscreen mode

Walk through the three outcomes:

  • Commit. The event flow completes. The stack is popped, finally clears gestureTarget, top is now the old previous, and the effect calls animateTo(top). The engine continues from the gesture's last values.
  • Cancel. The system cancels the handler’s coroutine, so collect throws CancellationException. The stack is untouched, finally clears gestureTarget, top is unchanged, and the effect calls animateTo(top), which settles the screen back where it was. One thing to test explicitly here: the reference says a property with no exit transition keeps its last manual value until the transition completes, and on a cancel the target never changes. Confirm on a device that the scale returns to full size, and if it does not, give the screen an explicit return path rather than relying on the handoff.
  • No gesture. A normal programmatic pop changes top, the effect calls animateTo, and the transition runs without ever entering the deferred phase.

Note the one place LaunchedEffect is deliberate: it is keyed on exactly the two inputs that decide the call, so it re-runs only when one of them changes.

Failure modes that only show up in production

failure-modes

1. Popping the stack when the gesture starts. It feels natural, because you need to know the previous screen. But the user may lift their finger early. A cancelled swipe then leaves the app on the wrong screen with an animation that says otherwise. Derive previous from the stack without mutating it, and pop only when the event flow completes.

2. Swallowing CancellationException. The flow signals a cancelled gesture by cancelling your handler's coroutine. A broad catch (e: Exception) turns cancel into something that falls through to the code you wrote for commit. Use try/finally, or rethrow. In the host above, the only code after collect runs on a clean completion, which is the entire point.

3. Resetting progress at the end of the gesture. This one comes from reasoning about the handoff rather than from a documented rule, so verify it on your own device. Between the moment the gesture ends and the moment the effect calls animateTo, there can be a frame where the transition is still deferred. If you have already zeroed swipeProgress, that frame draws the screen at full size, then the animation resumes from a different value: a visible snap. Resetting at the start of the next gesture avoids it.

4. Calling defer or animateTo straight from composition. The sample in the Android blog calls them inline to keep the snippet short. In a real screen that means a side effect on every recomposition, including ones unrelated to navigation. Key an effect on the inputs that matter. (Compose 1.12 also added keyed SideEffect overloads, which are cheaper than LaunchedEffect when you do not need a coroutine, if you confirm the calls are not suspending in your version.)

5. Losing screen state in a custom host. NavDisplay brings entry decorators for saved state and ViewModel scoping. A hand-rolled host does not. The moment a screen leaves composition, its rememberSaveable state is gone, and a cancelled swipe then reveals a freshly reset screen. Wrap each screen in a SaveableStateProvider keyed by something stable, as above, and give ViewModel scoping the same deliberate thought.

6. Missing opt-ins and flags. Predictive back needs the callback enabled on the platform side (android:enableOnBackInvokedCallback="true" for Android 13 and up unless your target SDK already defaults it on). On the Compose side, the release notes say the experimental opt-in for deferred transitions was removed in 1.13.0-alpha03, which implies that on 1.12 you should expect to opt in to ExperimentalDeferredTransitionApi.

A seventh, the dashed arrow in the state machine, deserves its own paragraph: re-grabbing during the settle. A user who swipes again while the commit animation is still running starts a gesture against a stack that has already changed. Decide your policy explicitly. The simplest is to disable the handler until the transition reports idle, accepting that rapid double-back feels slightly sticky. The nicer one lets defer take over mid-flight, which is the case the velocity-preserving handoff was built to make graceful, but it needs on-device testing with fast, repeated swipes before you trust it.

Shared elements and the deferred phase

If a shared element should follow the screen while the user is still dragging, SharedContentConfig gained permitTransformDuringDeferredTransition in 1.12. It controls whether shared elements visually transform together with their parent container during the deferred phase. Leave it off when the shared element should stay anchored until the decision is made; turn it on when you want the whole composition to feel like one physical sheet.

Testing

Gesture-driven animation is where flaky UI tests go to be born. Compose 1.12 added two helpers aimed at this: hasPendingWork checks for outstanding work without advancing the clock, and runWithoutImplicitWait suppresses the per-query synchronization so you can read several nodes within one frame. Combine them with mainClock.autoAdvance = false and step frames yourself. Assert three scenarios at minimum: a swipe that commits, a swipe that cancels (stack unchanged), and a programmatic pop that never enters the deferred phase.

Versions and caveats

  • The deferred transition APIs shipped with Compose 1.12 (BOM 2026.08.00), which raises compileSdk to 37 and requires AGP 9.1.2 or newer.
  • This is a young API surface, and the Android blog’s own sample passes a targetState argument that the published signature does not have, so trust the reference over snippets. Confirm the opt-in annotation and its import, and the properties available inside MutableContentTransform (the reference sample uses offset; scale appears in the blog sample), against the version you ship.
  • Use removeLastOrNull() rather than removeLast() on a SnapshotStateList. With compileSdk 35 or higher, removeLast() can resolve to the Java 21 List method and crash with NoSuchMethodError on older Android versions.
  • PredictiveBackHandler is still documented in the androidx.activity predictive back guide. Multiplatform projects have moved toward the Navigation Event library, whose handler separates cancel and complete callbacks instead of using a cancellable flow; the same host structure applies with onBackCompleted doing the pop.

The short version

Treat the back gesture as a held state, not an event. Hold with defer while the finger is down, release with exactly one animateTo whatever the outcome, mutate the back stack only on commit, and keep progress alive until the next gesture so the handoff has something smooth to start from. Get those four habits right and the rest is just choosing how far the screen shrinks.

References

📱 Level Up Your Android System Design Game

If you’re prepping for a senior Android role and system design rounds are the part that makes you sweat, I highly recommend “Mastering Android System Design” — a 37-chapter playbook that treats Android like the constrained runtime it actually is, not a small server. It covers Binder IPC, ART’s GC, process death, and background execution limits, then walks through the CRDDS interview framework and 13 full worked case studies (chat, ride-hailing, video streaming, payments, and more) carried end-to-end through API design, offline sync, and the Android-specific edge cases that trip candidates up mid-interview.

Top comments (0)