1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Jetpack Compose】ナビゲーションの連打・同時押しを防ぐ

Last updated at Posted at 2024-07-05

Lifecycle 2.8.0以降でdropUnlessResumed dropUnlessStarted というAPIが追加されています。
以下のように画面遷移のコードを囲うことで、ナビゲーションの連打・同時押しを防ぐことができます。

Button(
  onClick = dropUnlessResumed { navController.navigate(SCREEN) }
) {
  // ...
}

注意点

dropUnlessResumedの返り値は () -> Unit です。従って次のように書くことはできません。

@Composable
fun ScreenA() {
  Component(
    navigateToB = dropUnlessResumed { /* ... */ }
  )
}

@Composable
fun Component(
  navigateToB: (userId: String) -> Unit
) {
  // ...
}

内部実装

単純にライフサイクルをチェックしているだけのようです。

@Composable
fun dropUnlessResumed(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    block: () -> Unit,
): () -> Unit = dropUnlessStateIsAtLeast(State.RESUMED, lifecycleOwner, block)

@Composable
private fun dropUnlessStateIsAtLeast(
    state: State,
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    block: () -> Unit,
): () -> Unit {
    require(state != State.DESTROYED) { "..." }

    return {
        if (lifecycleOwner.lifecycle.currentState.isAtLeast(state)) {
            block()
        }
    }
}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?