0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Navigation3で遷移アニメーション中の遷移を抑制するには

0
Posted at

Navigation3使っていますか?

Navigation3に移行してちょっと困った状態になりました。
画面遷移時、遷移アニメーションの最中に次の画面遷移が発生すると、アニメーションがおかしくなります。pop動作なのにpushのアニメーションが再生される。enterとexitの前後関係が反転する。といった破綻が発生してしまうのです。
本来遷移アニメーションは画面の遷移を視覚的にわかりやすく伝えるためのものなのに、これではかえって混乱してしまいます。

遷移アニメーション中の画面遷移を抑制できれば良いのですが、遷移アニメーション中であることを知るためのインターフェイスがあるわけでもないので色々と工夫が必要です。
その工夫の仕方を解説しようと思います。

制限を設けるにあたって用途を限定しています。SinglePaneでの動作しか想定していません。どのアプリにでも適用できる汎用性のある実装ではありません。
制限のかけ方の一例や、Navigation3に細工を行うヒントとして読んでいただき、各アプリに適した実装へ変更して利用ください。

本記事はNavigation3 1.2.0時点で発生している問題について記述しています。Navigation3は遷移に伴う不具合が多く報告されており、いずれ修正されるものと考えられますが、すべての問題が解決するまでには時間がかかる可能性があります。それまでの「つなぎ」対策としてご覧ください。

NavigatorとNavGraphを用意する

Navigation3ではバックスタックはアプリが直接管理するポリシーです。
実態はただのリストなので任意の操作が可能なのですが、自由度が高すぎるので操作を行うオブジェクトを作成し、操作を集約するのが良いでしょう。
また、どの画面からどの画面に遷移が可能であるかというNavGraphを定義しておくと、意図しない遷移が発生しないことを明確にできます。
ここではバックスタックを操作するNavigatorと遷移の制約であるNavGraphを組み合わせて制御する方法を紹介します。

説明のため以下のようなNavKeyが定義されている前提としています。

@Serializable
internal sealed interface Screen : NavKey {
    @Serializable
    data object ScreenA : Screen
    @Serializable
    data object ScreenB : Screen
    @Serializable
    data object ScreenC : Screen
    @Serializable
    data object ScreenD : Screen
}

NavGraphを用意する

fromからtoへ遷移可能かを判定するメソッドをもたせます。

interface NavGraph<T : NavKey> {
    fun canNavigate(
        from: T,
        to: T,
    ): Boolean
}

実装としてはfromをkey、toのSetをvalueとして持つMapを持たせて判定するのが楽でしょう。

private class NavGraphImpl<T : NavKey>(
    private val graph: Map<KClass<out T>, Set<KClass<out T>>>,
) : NavGraph<T> {
    override fun canNavigate(
        from: T,
        to: T,
    ): Boolean = graph[from::class]?.contains(to::class) == true
}

Mapの定義は以下のようにmapOfで定義しても十分読みやすいとは思います。

NavGraphImpl(
    mapOf(
        ScreenA::class to setOf(
            ScreenB::class,
            ScreenC::class,
        ),
        ScreenB::class to setOf(
            ScreenD::class,
        ),
    ),
)

しかし、NavGraphを表していることがわかりにくかったり、要素が1つでもsetOf()が必要だったり、::classが冗長な印象になります。こういうときはDSLを作成しましょう。
以下のように実装すると

fun <T : NavKey> navGraph(
    action: NavGraphBuilder<T>.() -> Unit,
): NavGraph<T> = NavGraphImpl(NavGraphBuilder<T>().apply(action).build())

@DslMarker
annotation class NavGraphDsl

@NavGraphDsl
class NavGraphBuilder<T : NavKey> {
    private val graph = mutableMapOf<KClass<out T>, MutableSet<KClass<out T>>>()

    internal fun build(): Map<KClass<out T>, Set<KClass<out T>>> =
        graph.mapValues { it.value.toSet() }

    @PublishedApi
    internal fun addTransition(
        from: KClass<out T>,
        to: KClass<out T>,
    ) {
        graph.getOrPut(from) { mutableSetOf() }.add(to)
    }

    inline fun <reified From : T> from(
        action: NavGraphNodeScope<T>.() -> Unit,
    ) {
        NavGraphNodeScope(this, From::class).apply(action)
    }
}

@NavGraphDsl
class NavGraphNodeScope<T : NavKey> @PublishedApi internal constructor(
    @PublishedApi internal val builder: NavGraphBuilder<T>,
    @PublishedApi internal val fromClass: KClass<out T>,
) {
    inline fun <reified To : T> to() {
        builder.addTransition(fromClass, To::class)
    }
}

以下のようなシンプルな記述でNavGraphを定義できます。

internal val navGraph: NavGraph<Screen> = navGraph {
    from<ScreenA> {
        to<ScreenB>()
        to<ScreenC>()
    }
    from<ScreenB> {
        to<ScreenD>()
    }
}

NavGraphは動的に変化するものではないので、定数として保持しておきましょう。

このNavGraphはKeyのクラス単位での遷移可否を定義するのみです。同じクラスのパラメーターに基づく制約を表現することはd家いません。

Navigatorを用意する

遷移アニメーションに伴う制限をかける機能を追加するのも、このNavigatorです。まずはNavGraphに基づく遷移ができるように実装します。

遷移する際はfromとtoがNavGraphで定義された通りかをチェックしてから実行。
戻る場合は、現在の画面とbackStackの末尾が一致していることを確認してから戻る。
backStackはこのNavigatorの中でのみ操作するため、公開するbackStackフィールドはListにしています。

class Navigator<T : NavKey>(
    backStack: NavBackStack<T>,
    private val navGraph: NavGraph<T>,
    private val onExit: () -> Unit,
) {
    private val mutableBackStack = backStack
    val backStack: List<T> = mutableBackStack

    fun goBack(
        from: T? = null,
    ) {
        if (from != null && backStack.lastOrNull() != from) {
            return
        }
        if (backStack.size > 1) {
            mutableBackStack.removeLastOrNull()
        } else {
            onExit()
        }
    }

    fun navigate(
        to: T,
    ) {
        val from = backStack.lastOrNull() ?: return
        if (from == to) return // 連打対策
        if (!navGraph.canNavigate(from, to)) return
        mutableBackStack.add(to)
    }
}

このNavigatorはrememberして使うことになるので、以下のようにrememberNavigatorを定義して使います。
backStackはこの中で作っているので、外からMutableなListとしては見えないようになります。

@Composable
fun <T : NavKey> rememberNavigator(
    initialKey: T,
    navGraph: NavGraph<T>,
    onExit: () -> Unit,
): Navigator<T> {
    @Suppress("UNCHECKED_CAST")
    val backStack = rememberNavBackStack(initialKey) as NavBackStack<T>
    val currentOnExit by rememberUpdatedState(onExit)
    return remember(backStack, navGraph) {
        Navigator(
            backStack = backStack,
            navGraph = navGraph,
            onExit = { currentOnExit() },
        )
    }
}

使い方は以下のようになります。

val onBackPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
val navigator = rememberNavigator(Main, navGraph) {
    onBackPressedDispatcher?.onBackPressed()
}
val entryProvider = remember(navigator) { makeEntryProvider(navigator) }
NavigationDisplay(
    backStack = navigator.backStack,
    onBack = { navigator.goBack() },
    entryProvider = entryProvider,
    entryDecorators = ...,
    transitionSpec = ...,
    popTransitionSpec = ...,
    predictivePopTransitionSpec = ...,
)

entryProviderでは以下のように定義し、遷移はnavigatorを呼び出すようにします。entryのラムダには現在のnavKeyが渡されるので、goBackの引数にはこれをそのまま渡すのがよいです。

private fun makeEntryProvider(
    navigator: Navigator<Screen>,
): (Screen) -> NavEntry<Screen> =
    entryProvider {
        entry<ScreenA> {
            ScreenA(
                goToB = { navigator.navigate(ScreenB) },
                goToC = { navigator.navigate(ScreenC) },
            )
        }
        entry<ScreenB> { current ->
            ScreenB(
                goToD = { navigator.navigate(ScreenD) },
                goBack = { navigator.goBack(current) },
            )
        }
        ...
    }
}

遷移アニメーション中の判定を追加する

各entryのLifecycleを監視することで遷移可否の判定を行う作戦を取ってみます。

遷移アニメーションが開始されるとそのentryはResumed状態からStarted状態に変化します。
現在のentryがResumedのときのみ遷移可能と判定することにします。
この判定の仕組みをNavigatorに追加します。

class Navigator<T : NavKey>(
...
    private val entryLifecycles = mutableMapOf<T, Lifecycle>()
    internal var isNavigationReady by mutableStateOf(false)
        private set

    internal fun attachLifecycle(
        key: T,
        lifecycle: Lifecycle,
    ) {
        entryLifecycles[key] = lifecycle
        updateNavigationReadiness()
    }

    internal fun detachLifecycle(
        key: T,
        lifecycle: Lifecycle,
    ) {
        entryLifecycles.remove(key, lifecycle)
        updateNavigationReadiness()
    }

    internal fun updateNavigationReadiness() {
        val current = backStack.lastOrNull()
        isNavigationReady =
            entryLifecycles[current]?.currentState == Lifecycle.State.RESUMED
    }
    
    fun goBack(
        from: T? = null,
    ) {
        if (from != null && backStack.lastOrNull() != from) {
            return
        }
        if (!isNavigationReady) return
        if (backStack.size > 1) {
            mutableBackStack.removeLastOrNull()
            updateNavigationReadiness()
        } else {
            onExit()
        }
    }

    fun navigate(
        to: T,
    ) {
        val from = backStack.lastOrNull() ?: return
        if (from == to) return // 連打対策
        if (!navGraph.canNavigate(from, to)) return
        if (!isNavigationReady) return
        mutableBackStack.add(to)
        updateNavigationReadiness()
    }
}

entryLifecycles = mutableMapOf<T, Lifecycle>()なので同じKeyの画面がスタックされることは想定していません。

あとはentryProviderの各entryでこのメソッドを呼び出せばよいのですが、全部にもれなく実装するのは面倒ですし、漏れが出る可能性があります。
各entryごとに実行したい処理がある場合は、NavEntryDecoratorを実装するのが良いです。
以下のように実装し、Navigatorの各メソッドを呼び出します。

@Composable
fun <T : NavKey> rememberNavigatorNavEntryDecorator(
    navigator: Navigator<T>,
): NavEntryDecorator<T> =
    remember(navigator) {
        NavEntryDecorator { entry ->
            NavEntry(
                navEntry = entry,
                content = { key ->
                    val lifecycle = LocalLifecycleOwner.current.lifecycle
                    DisposableEffect(navigator, key, lifecycle) {
                        navigator.attachLifecycle(key, lifecycle)
                        val observer = LifecycleEventObserver { _, _ ->
                            navigator.updateNavigationReadiness()
                        }
                        lifecycle.addObserver(observer)
                        onDispose {
                            lifecycle.removeObserver(observer)
                            navigator.detachLifecycle(key, lifecycle)
                        }
                    }
                    entry.Content()
                },
            ).Content()
        }
    }

NavEntryからNavEntryを作ってContent()を二重に読んでいることに違和感があるかもしれません。
NavEntryDecoratorのdecorateラムダの引数はNavEntry<T>なのですが、NavKeyはprivateフィールドなので直接参照ができません。そのためコピーコンストラクターを使ってcontentを書き換える作戦を取っています。

これで遷移アニメーション中の遷移をブロックすることができる……のですが大きく2つの問題があります。
問題が起こるのはPredictiveBack(予測型戻る)の遷移です。
1つは、Predictive Backが開始した段階でentryはResumed状態ではなくなり、安全に遷移できない判定となってしまいます。
その後戻る操作が確定すると、この状態のままgoBackがコールされます。当然中で遷移がブロックされるため、Predictive Backが有効だと戻る操作ができなくなります。
もう1つは、前述の通り、Predictive Backの開始は遷移「前」であるため、Navigatorによる判定を受けることなく開始されてしまう点です。1つ前の遷移アニメーションが完了する前にPredictive Backが開始されると同様にアニメーションが破綻してしまいます。

Predictive Backの操作に割り込む対応が追加で必要です。

Predictive Backを制御する

Predictive BackはNavDisplayの中で実装されており、外部から制御する手段がありません。
そのため、NavDisplayの中身、Predictive Backの制御が行われているところまでを自前で実装する必要があります。

まずは通常利用するNavDisplayのコードを読んでみましょう。

NavDisplay.kt
@Composable
public fun <T : Any> NavDisplay(
    backStack: List<T>,
    modifier: Modifier = Modifier,
    contentAlignment: Alignment = Alignment.TopStart,
    onBack: () -> Unit = {
        if (backStack is MutableList<T>) {
            backStack.removeLastOrNull()
        }
    },
    entryDecorators: List<NavEntryDecorator<T>> =
        listOf(rememberSaveableStateHolderNavEntryDecorator()),
    sceneStrategies: List<SceneStrategy<T>> = listOf(SinglePaneSceneStrategy()),
    sceneDecoratorStrategies: List<SceneDecoratorStrategy<T>> = emptyList(),
    sharedTransitionScope: SharedTransitionScope? = null,
    sizeTransform: SizeTransform? = null,
    transitionSpec: AnimatedContentTransitionScope<Scene<T>>.() -> ContentTransform =
        defaultTransitionSpec(),
    popTransitionSpec: AnimatedContentTransitionScope<Scene<T>>.() -> ContentTransform =
        defaultPopTransitionSpec(),
    predictivePopTransitionSpec:
        AnimatedContentTransitionScope<Scene<T>>.(
            @NavigationEvent.SwipeEdge Int
        ) -> ContentTransform =
        defaultPredictivePopTransitionSpec(),
    entryProvider: (key: T) -> NavEntry<T>,
) {
    require(backStack.isNotEmpty()) { "NavDisplay backstack cannot be empty" }

    val entries =
        rememberDecoratedNavEntries(
            backStack = backStack,
            entryDecorators = entryDecorators,
            entryProvider = entryProvider,
        )

    NavDisplay(
        entries = entries,
        sceneStrategies = sceneStrategies,
        sceneDecoratorStrategies = sceneDecoratorStrategies,
        sharedTransitionScope = sharedTransitionScope,
        modifier = modifier,
        contentAlignment = contentAlignment,
        sizeTransform = sizeTransform,
        transitionSpec = transitionSpec,
        popTransitionSpec = popTransitionSpec,
        predictivePopTransitionSpec = predictivePopTransitionSpec,
        onBack = onBack,
    )
}

backStack、entryDecorators、entryProviderからentries: SceneState<T>を作成し、NavDisplayのオーバーロードを呼び出しています。
呼び出されている処理が以下です。

NavDisplay.kt
@Composable
public fun <T : Any> NavDisplay(
    entries: List<NavEntry<T>>,
    modifier: Modifier = Modifier,
    contentAlignment: Alignment = Alignment.TopStart,
    sceneStrategies: List<SceneStrategy<T>> = listOf(SinglePaneSceneStrategy()),
    sceneDecoratorStrategies: List<SceneDecoratorStrategy<T>> = emptyList(),
    sharedTransitionScope: SharedTransitionScope? = null,
    sizeTransform: SizeTransform? = null,
    transitionSpec: AnimatedContentTransitionScope<Scene<T>>.() -> ContentTransform =
        defaultTransitionSpec(),
    popTransitionSpec: AnimatedContentTransitionScope<Scene<T>>.() -> ContentTransform =
        defaultPopTransitionSpec(),
    predictivePopTransitionSpec:
        AnimatedContentTransitionScope<Scene<T>>.(
            @NavigationEvent.SwipeEdge Int
        ) -> ContentTransform =
        defaultPredictivePopTransitionSpec(),
    onBack: () -> Unit,
) {
    require(entries.isNotEmpty()) { "NavDisplay entries cannot be empty" }

    val sceneState =
        rememberSceneState(
            entries,
            sceneStrategies,
            sceneDecoratorStrategies,
            sharedTransitionScope,
            onBack,
        )
    val scene = sceneState.currentScene

    // Predictive Back Handling
    val currentInfo = SceneInfo(scene)
    val previousSceneInfos = sceneState.previousScenes.map { SceneInfo(it) }
    val gestureState =
        rememberNavigationEventState(currentInfo = currentInfo, backInfo = previousSceneInfos)

    NavigationBackHandler(
        state = gestureState,
        isBackEnabled = scene.previousEntries.isNotEmpty(),
        onBackCompleted = {
            // If `enabled` becomes stale (e.g., it was set to false but a gesture was
            // dispatched in the same frame), this may result in no entries being popped
            // due to entries.size being smaller than scene.previousEntries.size
            // but that's preferable to crashing with an IndexOutOfBoundsException
            repeat(entries.size - scene.previousEntries.size) { onBack() }
        },
    )

    NavDisplay(
        sceneState,
        gestureState,
        modifier,
        contentAlignment,
        sizeTransform,
        transitionSpec,
        popTransitionSpec,
        predictivePopTransitionSpec,
    )
}

バックキーをハンドリングしている箇所が見えました。
rememberSceneStateにもonBackが渡されていますが、これはSceneの都合でバック処理が必要な場合に呼び出されるものです。デフォルトのSinglePaneSceneStrategyでは呼び出されないようですが、Scene都合のバックを無視してしまうと破綻する可能性があるため、ここからのリクエストは遷移アニメーション中だからといって無効化できません。

NavigationBackHandlerこれがバックキーやスワイプバックのジェスチャーを受けている部分です。
isBackEnabledがfalseだとジェスチャーを受け取らなくなり、Activityなど上位コンポーネントが受けることになります。遷移アニメーション中のPredictive Backを無効化するには、isEnabledをfalseに設定し、その代わりイベントをActivityが受け取らないようにブロックすればよいです。

onBackCompletedがPredictive Backを含めてバック操作が確定したときに呼ばれます。
また、onBackCancelledというラムダを指定することもできて、Predictive Backを開始したが、バック操作に至らなかった場合に呼び出されます。

あと必要な情報は、Predictive Backの開始です。これはgestureState: NavigationEventState<T>から取得できます。

internal fun NavigationEventState<*>.isPredictiveBackInProgress(): Boolean {
    val state = transitionState
    if (state !is NavigationEventTransitionState.InProgress) return false
    return state.direction == NavigationEventTransitionState.TRANSITIONING_BACK
}

transitionStateがInProgressであり、それが戻り(TRANSITIONING_BACK)であればPredictive Backと判定します。

Navigatorの変更

Predictive Backの制御を入れるため前項で調べた処理をNavigatorで受け取れるようにします。
Navigationアプリ上で実装した戻るナビゲーションを処理するgoBack以外に、システムからの戻りを処理するonSystemBackを追加します。
Predictive Back中など、isNavigationReadyの状態を無視して戻らせる必要があるので、それを表すBooleanと複数のスタックをまとめて戻る操作に対応するためのpopCountを引数に持たせています。

    fun goBack(
        from: T? = null,
    ) {
        navigateBack(from)
    }

    internal fun onSystemBack(
        ignoreNavigationReady: Boolean,
        popCount: Int = 1,
    ) {
        navigateBack(from = null, ignoreNavigationReady = ignoreNavigationReady, popCount = popCount)
    }

    private fun navigateBack(
        from: T?,
        ignoreNavigationReady: Boolean = false,
        popCount: Int = 1,
    ) {
        if (popCount <= 0) return
        if (from != null && backStack.lastOrNull() != from) {
            return
        }
        if (!ignoreNavigationReady && !isNavigationReady) {
            return
        }
        pendingNavigation = null
        if (backStack.size > 1) {
            repeat(popCount.coerceAtMost(backStack.size - 1)) {
                mutableBackStack.removeLastOrNull()
            }
            updateNavigationReadiness()
        } else {
            onExit()
        }
    }

NavDisplayのカスタマイズ

NavDisplayのオーバーロードでも良いかもしれませんが、ライブラリ提供のメソッドのオーバーロードは混乱する可能性があるので、NavigationDisplayという名前でカスタマイズ版を作成します。

@Composable
fun <T : NavKey> NavigationDisplay(
    navigator: Navigator<T>,
    modifier: Modifier = Modifier,
    sceneStrategies: List<SceneStrategy<T>> = listOf(SinglePaneSceneStrategy()),
    entryProvider: (key: T) -> NavEntry<T>,
) {
    val entries = rememberDecoratedNavEntries(
        backStack = navigator.backStack,
        entryDecorators = listOf(
            rememberSaveableStateHolderNavEntryDecorator(),
            rememberViewModelStoreNavEntryDecorator(),
            rememberNavigatorNavEntryDecorator(navigator),
        ),
        entryProvider = entryProvider,
    )
    val sceneState = rememberSceneState(
        entries = entries,
        sceneStrategies = sceneStrategies,
        onBack = {
            // Scene都合でのBackはtransition中でも無効化しない
            navigator.onSystemBack(true)
        },
    )

    val scene = sceneState.currentScene
    val gestureState = rememberNavigationEventState(
        currentInfo = SceneInfo(scene),
        backInfo = sceneState.previousScenes.map { SceneInfo(it) },
    )
    val isPredictiveBackInProgress = gestureState.isPredictiveBackInProgress()
    // ★ 必要なのは現在PredictiveBackか否かではなく、PredictiveBackからbackが確定したか否かなので、履歴情報として保持する
    var isPredictiveBackActive by remember { mutableStateOf(false) }
    SideEffect(isPredictiveBackInProgress) {
        if (isPredictiveBackInProgress) {
            isPredictiveBackActive = true
        }
    }
    val isBackNavigationEnabled =
        scene.previousEntries.isNotEmpty() && navigator.isNavigationReady

    NavigationBackHandler(
        state = gestureState,
        isBackEnabled = isBackNavigationEnabled,
        onBackCancelled = {
            isPredictiveBackActive = false
        },
        onBackCompleted = {
            val fromPredictiveBack = isPredictiveBackActive
            isPredictiveBackActive = false
            navigator.onSystemBack(
                // ★ PredictiveBackからの場合はisNavigationReadyを無視する
                ignoreNavigationReady = fromPredictiveBack,
                popCount = entries.size - scene.previousEntries.size,
            )
        },
    )
    // ★ NavigationBackHandlerを無効化している間、Activityにジェスチャーを伝えない
    BackHandler(enabled = !navigator.isNavigationReady, onBack = {})

    NavDisplay(
        sceneState = sceneState,
        navigationEventState = gestureState,
        modifier = modifier,
        transitionSpec = NavigationSpec.push(),
        popTransitionSpec = NavigationSpec.pop(),
        predictivePopTransitionSpec = NavigationSpec.predictivePop(),
    )
}

@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun NavigationEventState<*>.isPredictiveBackInProgress(): Boolean {
    val state = transitionState
    if (state !is NavigationEventTransitionState.InProgress) return false
    return state.direction == NavigationEventTransitionState.TRANSITIONING_BACK
}

これで、遷移アニメーション中にPredictive Backが開始することはなく、Predictive Backによる戻る確定時の戻る操作を実行させることができます。

遅延実行

基本前項までの対応で問題は解消していると思います。
しかし、遷移アニメーションの終了は人間が見えているよりもわずかに遅いなど、単に遷移を無効化するだけではわずか数ミリ秒の違いで操作できるできないが分かれてしまい、ユーザビリティが悪くなってしまいます。
無効化すると同時に操作をキャッシュしておき、遷移アニメーションの完了時に取っておいたナビゲーションを実行するとこの違和感をある程度軽減させることができます。

class Navigator<T : NavKey>(
    backStack: NavBackStack<T>,
    private val navGraph: NavGraph<T>,
    private val onExit: () -> Unit,
) {
    private val mutableBackStack = backStack
    val backStack: List<T> = mutableBackStack

    private val entryLifecycles = mutableMapOf<T, Lifecycle>()
    private var pendingNavigation: (() -> Unit)? = null
    internal var isNavigationReady by mutableStateOf(false)
        private set

    fun goBack(
        from: T? = null,
    ) {
        navigateBack(from)
    }

    internal fun onSystemBack(
        ignoreNavigationReady: Boolean,
        popCount: Int = 1,
    ) {
        navigateBack(from = null, ignoreNavigationReady = ignoreNavigationReady, popCount = popCount)
    }

    private fun navigateBack(
        from: T?,
        ignoreNavigationReady: Boolean = false,
        popCount: Int = 1,
    ) {
        if (popCount <= 0) return
        if (from != null && backStack.lastOrNull() != from) {
            return
        }
        if (!ignoreNavigationReady && !isNavigationReady) {
            enqueueNavigation { navigateBack(from, popCount = popCount) }
            return
        }
        pendingNavigation = null
        if (backStack.size > 1) {
            repeat(popCount.coerceAtMost(backStack.size - 1)) {
                mutableBackStack.removeLastOrNull()
            }
            updateNavigationReadiness()
        } else {
            onExit()
        }
    }

    fun navigate(
        to: T,
    ) {
        val from = backStack.lastOrNull() ?: return
        if (from == to) {
            return // 連打無効
        }
        if (!navGraph.canNavigate(from, to)) {
            return
        }
        if (!isNavigationReady) {
            enqueueNavigation { navigate(to) }
            return
        }
        mutableBackStack.add(to)
        updateNavigationReadiness()
    }

    private fun enqueueNavigation(
        action: () -> Unit,
    ) {
        if (pendingNavigation == null) {
            pendingNavigation = action
        }
    }

    internal fun attachLifecycle(
        key: T,
        lifecycle: Lifecycle,
    ) {
        entryLifecycles[key] = lifecycle
        updateNavigationReadiness()
    }

    internal fun detachLifecycle(
        key: T,
        lifecycle: Lifecycle,
    ) {
        entryLifecycles.remove(key, lifecycle)
        updateNavigationReadiness()
    }

    internal fun updateNavigationReadiness() {
        val current = backStack.lastOrNull()
        isNavigationReady = entryLifecycles[current]?.currentState == Lifecycle.State.RESUMED
        if (isNavigationReady) {
            val action = pendingNavigation
            pendingNavigation = null
            action?.invoke()
        }
    }
}

Navigation3自体の問題や、アプリで使う上での不都合があった場合でも、諦める必要はありません。
中の処理を分解し、ある程度のところを自作することで問題を解決し、そのアプリに適したナビゲーションを実装できます。
冒頭で述べたように、ここで紹介した方法はどのアプリにも適用できるような方法ではありませんが、この情報をヒントにご自身のアプリに適したナビゲーションの実装につながれば幸いです。

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?