skip to content

In Compose, a bouquet card's Animatable settle animation is grabbed mid-flight and the code after animateTo never runs; why, and how should drag, release and settle use the Animatable?

level: seniorimportance: should knowfreq 40%

answer

  1. one value holder, one animation at a time
  2. MutatorMutex: newest caller wins
  3. cancelled animateTo throws CancellationException
  4. stop on touch, snapTo while dragging
  5. initialVelocity only after a fling

basics

~20 s

Animatable runs one animation at a time: animateTo, animateDecay, snapTo or stop from another coroutine cancels the running one. The cancelled animateTo throws CancellationException, so code after it never runs. Stop on touch, snapTo during drag, animateTo on release.

solid answer

~40 s

`Animatable` guarantees mutual exclusion: starting `animateTo` or `animateDecay`, or calling `snapTo` or `stop`, cancels any animation in flight. The caller suspended in the cancelled `animateTo` gets a **`CancellationException`**, so an `onSettled()` call placed after it is skipped. That is usually what you want, because the user grabbed the card again. Wire it as: `stop()` on touch down, `snapTo(value + delta)` for each drag event, then on release `animateTo(0f, spring(...), initialVelocity = flingVelocity)` or `animateDecay(velocity, splineBasedDecay(density))` to throw it off. `animateTo` already continues from the current value and velocity; the KDoc recommends passing `initialVelocity` only right after a fling. Check `AnimationResult.endReason` (`Finished` or `BoundReached`) for completion, and put any cleanup in `try`/`finally`.

code

kotlin · 17 lines
kotlin
class CardSwipeState(private val scope: CoroutineScope) {
    val offsetX = Animatable(0f)

    fun onDragStart() = scope.launch { offsetX.stop() }

    fun onDrag(delta: Float) = scope.launch { offsetX.snapTo(offsetX.value + delta) }

    fun onRelease(velocity: Float, onSettled: () -> Unit) = scope.launch {
        val result = offsetX.animateTo(
            targetValue = 0f,
            animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
            initialVelocity = velocity,
        )
        // Not reached if a new drag cancels the settle: animateTo throws CancellationException.
        if (result.endReason == AnimationEndReason.Finished) onSettled()
    }
}

go deeper

for a junior

Recall that Animatable holds one value and offers animateTo, snapTo and stop, all suspend functions called from a coroutine.

for a middle

Explain mutual exclusion: any new call cancels the running animation and continues from the current value and velocity. Explain how snapTo and stop differ.

for a senior

Diagnose the skipped callback as the CancellationException a cancelled animateTo throws, and fix it with endReason checks and try/finally rather than swallowing the exception.

for a principal

Encapsulate gesture-driven Animatables in a state holder with one owner, so screens do not race several coroutines over the same value.

## Animatable in one paragraph **`Animatable`** is a coroutine-based holder for a single animated value. It is the low-level API that `animate*AsState` is built on. You create it with an initial value (`Animatable(0f)`, or `Animatable(Color.Gray)` for colours) and remember it in composition. Its suspend functions change the value: `animateTo`, `animateDecay`, `snapTo` and `stop`. Because they suspend, you call them from a coroutine: a `LaunchedEffect`, a scope from `rememberCoroutineScope()` for event callbacks, or the gesture-detection coroutine itself. ## The rule that explains the bug: one mutation at a time The documentation says `Animatable` ensures **consistent continuation and mutual exclusiveness**: the value never jumps unexpectedly, and only one operation runs at a time. Starting a new one **cancels** whatever is running: - `animateTo` or `animateDecay` cancels a running animation and continues from the current **value and velocity**. - `snapTo(target)` cancels it and sets the value at once, clamped to any bounds. - `stop()` cancels it and leaves the value where it is. It does not jump to the target. The KDoc then names the consequence: the **cancelled `animateTo` throws `CancellationException`**, so all the subsequent work in the caller's coroutine is cancelled too. In the flower-shop app, a released card springs back to centre and then calls `onSettled()` to record the swipe. If the customer grabs the card mid-settle, the drag's `stop()` or `snapTo()` cancels the settle, `animateTo` throws, and `onSettled()` never runs. The library is behaving as documented. The bug is code that assumes `animateTo` always returns. ## Wiring a gesture to an Animatable Detecting the touch belongs to the gesture modifiers. The animation side follows a fixed pattern, which the advanced gesture guide in the Android documentation shows: 1. **Touch down:** `offsetX.stop()` intercepts any running settle or fling. 2. **Each drag event:** `offsetX.snapTo(offsetX.value + delta)` makes the value follow the finger with no animation. 3. **Release:** read the velocity from a velocity tracker, then either - `offsetX.animateTo(targetValue = 0f, animationSpec = spring(...), initialVelocity = velocity)` to spring back, or - `offsetX.animateDecay(velocity, splineBasedDecay(density))` to let a fling glide to a stop. 4. **Bounds:** `offsetX.updateBounds(lowerBound, upperBound)` clamps the value. An animation that hits a bound ends with `AnimationEndReason.BoundReached` instead of `Finished`. ## initialVelocity and momentum `animateTo`'s `initialVelocity` defaults to the Animatable's **current velocity**, so an animation redirected mid-flight keeps its momentum. The KDoc recommends setting `initialVelocity` only when `animateTo` follows a fling, since altering velocity otherwise causes a visible discontinuity. Once an animation ends, the Animatable's velocity resets to 0. The velocity at that moment is preserved in the returned `AnimationResult.endState`, which you can feed into the next animation if the momentum should continue. ## Why not animate*AsState here `animateFloatAsState` is built on `Animatable`, but it hides the operations a gesture needs. It cannot be stopped or snapped, and a finger cannot write the value directly; it only follows a target computed from state. A draggable card needs all three: `stop()` when touched, `snapTo` while moving, and an animation with a chosen velocity on release. That is why gesture-driven values are held in an `Animatable` that a single owner, often a small state holder class, controls. ## Handling completion and cancellation correctly | Situation | What `animateTo` does | What your code should do | |---|---|---| | Reaches the target | returns `AnimationResult` with `endReason == Finished` | run `onSettled()` | | Hits a bound | returns with `endReason == BoundReached` | handle the edge, for example dismiss | | Interrupted by another call | throws `CancellationException` | let it propagate; clean up in `finally` | - Do **not** catch and swallow `CancellationException` to "force" the callback. That fights the coroutine's cancellation. - Put cleanup that must always happen, such as clearing a "settling" flag, in `try { ... } finally { ... }`. - Use `isRunning` and `targetValue` to inspect state; read `value` in a layout or draw lambda for per-frame position. ## Common mistakes - Starting `animateTo` from a `LaunchedEffect` keyed on state that the drag also changes, so each change restarts the effect and cancels the settle. - Creating a new `Animatable` on every recomposition by forgetting `remember`. The value then resets on each recomposition. - Choosing `tween` for a settle that users interrupt often. A spring carries the velocity across interruptions; a tween restarts its duration. - Using `animate*AsState` where the gesture must stop the value. It cannot be stopped without leaving composition.

  • How do you make sure a settling flag is cleared even when the user interrupts the settle?
    Wrap the `animateTo` call in `try { ... } finally { settling = false }`. When a newer `snapTo` or `stop` cancels the animation, `animateTo` throws `CancellationException`; the `finally` block still runs, and the exception keeps propagating, so the coroutine cancels cleanly.
  • When does animateTo return BoundReached instead of Finished?
    When bounds have been set with `updateBounds` and the animated value crosses one. The value is clamped and the animation ends with `AnimationEndReason.BoundReached`, usually short of the target and with remaining velocity, which `AnimationResult.endState` preserves.
  • Why does the KDoc warn against always passing initialVelocity to animateTo?
    Because `animateTo` already continues from the current velocity. Overriding it outside the hand-off from a fling makes the motion change speed abruptly, a visible discontinuity. Pass it when the velocity comes from the user's release gesture.

An Animatable is like one steering wheel with no co-pilot: whoever grabs it last is driving, and the previous driver's planned route, including whatever they meant to do on arrival, is abandoned.

  • A cancelled animateTo returns normally with its last value.
  • snapTo waits for the running animation to finish first.
  • stop() jumps the value to the animation's target.
  • Catching CancellationException is the right way to force onSettled.
  • Every animateTo call should pass initialVelocity explicitly.
  • animateDpAsState can be stopped mid-drag like an Animatable.