Merge "Don't let enabled state cancel active handlers" into androidx-main
diff --git a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt
index 169e92a2..326ad57 100644
--- a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt
+++ b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt
@@ -211,8 +211,8 @@
         // but since we idle here, we can cancel the callback channel and keep from completing
         rule.runOnIdle { assertThat(started).isTrue() }
         dispatcher.api34Complete()
-        rule.runOnIdle { assertThat(result).isEmpty() }
-        rule.runOnIdle { assertThat(cancelled).isTrue() }
+        rule.runOnIdle { assertThat(result).isEqualTo(listOf("onBack")) }
+        rule.runOnIdle { assertThat(cancelled).isFalse() }
     }
 
     fun testPredictiveBackHandlerDisabledAfterStart() {
diff --git a/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt b/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt
index 27364c8..67e3f8e 100644
--- a/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt
+++ b/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt
@@ -140,10 +140,11 @@
     var currentOnBack: suspend (progress: Flow<BackEventCompat>) -> Unit,
 ) : OnBackPressedCallback(enabled) {
     private var onBackInstance: OnBackInstance? = null
+    private var isActive = false
 
     fun setIsEnabled(enabled: Boolean) {
         // We are disabling a callback that was enabled.
-        if (!enabled && isEnabled) {
+        if (!enabled && !isActive && isEnabled) {
             onBackInstance?.cancel()
         }
         isEnabled = enabled
@@ -158,6 +159,7 @@
         if (isEnabled) {
             onBackInstance = OnBackInstance(onBackScope, true, currentOnBack, this)
         }
+        isActive = true
     }
 
     override fun handleOnBackProgressed(backEvent: BackEventCompat) {
@@ -184,6 +186,7 @@
         // but let the job complete normally
         onBackInstance?.close()
         onBackInstance?.isPredictiveBack = false
+        isActive = false
     }
 
     override fun handleOnBackCancelled() {
@@ -191,5 +194,6 @@
         // cancel will purge the channel of any sent events that are yet to be received
         onBackInstance?.cancel()
         onBackInstance?.isPredictiveBack = false
+        isActive = false
     }
 }