From 36cb809cc4241b8bd30bd7cddfddd1a2bb0f1f42 Mon Sep 17 00:00:00 2001 From: Yongshun Shreck Ye Date: Sun, 5 Jan 2025 00:32:04 +0800 Subject: [PATCH] Simplify and improve `previousBackStackEntry` in `NavController` `asReversed` is used instead of `reversed` to reduce the cost of copying a list. The reversed list is converted to a `Sequence` earlier and `drop(1)` is used instead of the iterator to simplify the code. --- .../src/main/java/androidx/navigation/NavController.kt | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/navigation/navigation-runtime/src/main/java/androidx/navigation/NavController.kt b/navigation/navigation-runtime/src/main/java/androidx/navigation/NavController.kt index 1174a14806bf6..696b1f5c8448c 100644 --- a/navigation/navigation-runtime/src/main/java/androidx/navigation/NavController.kt +++ b/navigation/navigation-runtime/src/main/java/androidx/navigation/NavController.kt @@ -2963,14 +2963,10 @@ public open class NavController( * two visible entries */ public open val previousBackStackEntry: NavBackStackEntry? - get() { - val iterator = backQueue.reversed().iterator() + get() = backQueue.asReversed().asSequence() // throw the topmost destination away. - if (iterator.hasNext()) { - iterator.next() - } - return iterator.asSequence().firstOrNull { entry -> entry.destination !is NavGraph } - } + .drop(1) + .firstOrNull { entry -> entry.destination !is NavGraph } public companion object { private const val TAG = "NavController"