Skip to content

Commit

Permalink
Fix SearchBar PredictiveBack's animation when a back action was cance…
Browse files Browse the repository at this point in the history
…led.

It is not possible to run a suspend function when the progress flow is canceled because the onBack suspend lambda is canceled as well. See: androidx.activity.compose.OnBackInstance.cancel
  • Loading branch information
terrakok committed Jan 17, 2025
1 parent 73fbc8a commit 15aa84a
Showing 1 changed file with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
Expand Down Expand Up @@ -125,6 +126,7 @@ import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.math.sign
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
* <a href="https://m3.material.io/components/search/overview" class="external"
Expand Down Expand Up @@ -183,6 +185,7 @@ fun SearchBar(
windowInsets: WindowInsets = SearchBarDefaults.windowInsets,
content: @Composable ColumnScope.() -> Unit,
) {
val coroutineScope = rememberCoroutineScope()
val animationProgress = remember { Animatable(initialValue = if (expanded) 1f else 0f) }
val finalBackProgress = remember { mutableFloatStateOf(Float.NaN) }
val firstBackEvent = remember { mutableStateOf<BackEventCompat?>(null) }
Expand Down Expand Up @@ -220,13 +223,15 @@ fun SearchBar(
finalBackProgress.floatValue = animationProgress.value
onExpandedChange(false)
} catch (e: CancellationException) {
animationProgress.animateTo(
targetValue = 1f,
animationSpec = AnimationPredictiveBackExitFloatSpec
)
finalBackProgress.floatValue = Float.NaN
firstBackEvent.value = null
currentBackEvent.value = null
coroutineScope.launch {
animationProgress.animateTo(
targetValue = 1f,
animationSpec = AnimationPredictiveBackExitFloatSpec
)
finalBackProgress.floatValue = Float.NaN
firstBackEvent.value = null
currentBackEvent.value = null
}
}
}
}
Expand Down

0 comments on commit 15aa84a

Please sign in to comment.