Hiltのナビゲーション引数で SavedStateHandle から卒業する

なぜ Hilt 2.49+ と @AssistedInject が、完全な型安全性を備えた引数渡しの「正解」と言えるのか。

 

🤔 問題点:静的な依存関係と動的なデータの混在

Android開発において、ViewModelにランタイム引数(実行時引数)を注入することは、常に議論の的となってきました。

その本質は、「静的依存関係」(DIによって管理されるリポジトリなど)と、「動的データ」(画面遷移時に渡されるナビゲーション引数など)の対立にあります。

適切なDIパターンを適用せずにこの問題に対処しようとすると、高確率でアンチパターンに陥ります。たとえば、一時的な状態をシングルトン(Singleton)内に保持してしまうと、状態の汚染や画面間でのデータ漏洩といった致命的なバグを引き起こす危険性があります。

 

🤔 解決策:ハイブリッド注入を実現する @AssistedInject

この「静的」と「動的」のギャップを埋めるための最適なツールが、@AssistedInject です。これを使用することで、DI(Hilt)が管理するオブジェクトと、実行時に受け取るランタイムパラメータをスマートに組み合わせた「ハイブリッド注入」が可能になります。

通常の @Inject は不要 :
@AssistedInject を使用する場合、コンストラクタに通常の @Inject を付ける必要はありません(というか、付けてはいけません)。

関心の分離 :
リポジトリなどの依存関係は Hilt が自動で供給し、ナビゲーション引数などの動的なデータだけを手動で安全に渡す、という明確な役割分担(関心の分離)が実現します。

クリーンなコードへ :
これにより、バグの温床になりがちだった危険な lateinit var による後からの初期化コードとは、完全におさらばできます。


// ViewModel 実装

@HiltViewModel(assistedFactory = RouteBViewModel.Factory::class) 
class  RouteBViewModel  @AssistedInject constructor( 
    private val repository: MyRepository,
    @Assisted val navKey: RouteB,
) : ViewModel() { 

    @AssistedFactory
    interface Factory { 
        fun create (navKey: RouteB) : RouteBViewModel 
    } 
}

 

🤔 実装:assistedFactory と hiltViewModel の組み合わせ

公式の nav3-recipes リポジトリでは、Hilt 2.49 以降で導入された最新の標準的な実装パターンが示されています。

ファクトリの宣言 :
@HiltViewModel(assistedFactory = ...) を使用して、Assisted Factory を ViewModel に直接リンクさせます。

2つの型パラメータ: Compose 側では、hiltViewModel() のように両方の型を明示的に指定して呼び出します。

安全なライフサイクル管理 :
creationCallback を利用することで、ナビゲーションのバックスタック管理(Lifecycle)を壊すことなく、安全にランタイム引数を渡すことができます。


// UI(ナビゲーション定義)

 entry<RouteB> { key -> 
    val viewModel = hiltViewModel<RouteBViewModel, RouteBViewModel.Factory>( 
        creationCallback = { factory -> 
            factory.create(key) 
        } 
    ) 
    ScreenB(viewModel = viewModel) 
}

 

🤔 メリット:100%の型安全性を実現し、SavedStateHandle のボイラープレートを完全に排除

このアーキテクチャ(Navigation 3 + @AssistedInject)に移行することで、コードベースの品質は大幅に向上します。

完全な型安全性(100% Type-Safe):
かつての文字列ベースのキー(string のキー指定)は過去のものです。ナビゲーション引数は、Route(Serializable等で定義された型)として、厳密に型指定されたオブジェクトのまま直接安全に渡されます。

SavedStateHandle からの解放 :
単に次の画面へ引数を渡すだけのために、SavedStateHandle を使ってごにょごにょと値を書き出したり読み出したりする定型文(ボイラープレート)はもう一切不要になります。

圧倒的なリファクタリングのしやすさ :
すべてがコンパイル時にチェックされるため、引数の追加・削除・変更といったリファクタリングが、一瞬かつ確実に(ランタイムエラーの心配なく)行えるようになります。

 

🤔 まとめ

Hilt と最新の Jetpack Navigation の相乗効果により、画面間の引数の受け渡しは驚くほどスムーズかつ洗練されたものになりました。もはや、型安全性を犠牲にしたり、不自然なアーキテクチャで回避策(ワークアラウンド)を講じたりする必要はありません。

@AssistedInject と、進化した hiltViewModel() API を組み合わせることで、「完璧な型安全性」と「クリーンなハイブリッド依存性注入(DI)」を今すぐあなたのプロジェクトに導入できます。


【Jetpack Compose Navigation3】EntryDecorator と ViewModel の「key」の深い関係

Jetpack Compose の Navigation3 では、画面遷移の引数として RouteB(val id: String) のようなデータクラスを渡します。

このとき、同じ RouteB でも id が違えば「別の画面(別の ViewModel)」として扱いたいですよね。

ここで重要になるのが EntryDecoratorviewModel(key = ...) の関係です。

 

🤔 結論:Decorator が「鍵」を管理してくれるか否か

一言でいうと、こうなります。

Decorator を使わない場合:
手動で viewModel(key = "unique_id") を指定する必要がある。

Decorator を使えば:
viewModel() の引数は不要。
Decorator が自動で各エントリに個別の ViewModelStore を割り当ててくれる。

 

🤔 1. Decorator を使わないパターン(手動管理)

Navigation3 の基本機能 NavDisplay を使う場合、ViewModel の生存期間はデフォルトの「Activity 全体」に紐づきます。

同じ RouteB でも id ごとに ViewModel を作り分けたい場合、以下のように手動で key を渡して、内部のキャッシュを分ける必要があります。


entry<RouteB> { key ->
    // key(RouteBのインスタンス)の id を使って、ViewModelを区別する
    val vm = viewModel(
        key = key.id, // ← これが必要!
        factory = RouteBViewModel.Factory(key)
    )
    ScreenB(vm)
}

これを忘れると、id = "1" の画面から id = "2" の画面へ遷移しても、同じ ViewModel インスタンスが使い回されてしまい、表示内容が更新されない というバグに繋がります。

 

🤔 2. Decorator を使うパターン(Navigation3 の推奨)

サンプルの BasicViewModelsActivity で採用されている方法です。

NavDisplay の設定に rememberViewModelStoreNavEntryDecorator() を追加します。


NavDisplay(
    backStack = backStack,
    entryDecorators = listOf(
        rememberSaveableStateHolderNavEntryDecorator(),
        rememberViewModelStoreNavEntryDecorator() // ← これが魔法のスパイス
    ),
    entryProvider = entryProvider {
        entry<RouteB> { key ->
            // key 指定が不要になる!
            val vm = viewModel(factory = RouteBViewModel.Factory(key))
            ScreenB(vm)
        }
    }
)

なぜ key が不要になるのか?

ViewModelStoreNavEntryDecorator は、バックスタックにある 「各エントリ(NavEntry)」ごとに独立した ViewModelStore を生成してくれます。

RouteB("1") のエントリ ➔ 専用の ViewModelStore A が用意される

RouteB("2") のエントリ ➔ 専用の ViewModelStore B が用意される

viewModel() 関数は、その時点の LocalViewModelStoreOwner(Decorator が提供するエントリごとのストア)を参照します。そのため、わざわざ key を指定しなくても、エントリが違えば自動的に別の ViewModel が作られる仕組みです。

 

🤔 まとめ:どっちを使うべき?

基本的には「Decorator を使う」のが正解です。

理由1:
コードがシンプルになる(key の指定漏れがなくなる)。

理由2:
画面を戻ったときに ViewModel が正しく破棄されるなど、ライフサイクル管理が Navigation3 のエントリと完全に同期する。

「この画面だけは特殊な管理をしたい」という場合を除き、rememberViewModelStoreNavEntryDecorator() をセットアップして、型安全な key をそのまま Factory に渡すスタイルを基本にしましょう。


Jetpack Compose Foundation サンプル目次リンク

Jetpack Composeの核心を担う androidx.compose.foundation

そのサンプルコード群は、Googleのエンジニアが「正しい書き方」を提示している宝庫です。

今回は、これらを実務での利用頻度とモダンな設計(2026年現在のトレンド)に基づいてグループ分けしました。

 

🧑🏻‍💻 1. インタラクション & ジェスチャー(操作感のキモ)

ユーザーが画面に触れた時の挙動を制御する、最も重要なグループです。

 

🧑🏻‍💻 2. スクロール & リスト(データの表示)

効率的にスクロールさせるためのテクニック集です。

 

🧑🏻‍💻 3. テキスト & 入力(文字の表示と編集)

2026年のトレンドである「次世代入力」が含まれます。

 

🧑🏻‍💻 4. 描画 & 視覚効果(見た目のクオリティ)

 

🧑🏻‍💻 5. 高度なシステム統合・同期

 

🧑🏻‍💻 これだけは読んでおくべきトップ5

1. ClickableSamples.kt(すべての基本)
2. LazyDslSamples.kt(リスト表示の要)
3. AnchoredDraggableSample.kt(モダンなUIに必須)
4. BasicTextFieldSamples.kt(入力の実装)
5. CanvasSamples.kt(カスタムUIの第一歩)

ぐらいか。


Modernizing Android Build Scripts: Moving from "android { ... }" to "configure { ... }"

In the world of Android development, Kotlin DSL has become the standard for writing build scripts.

While the familiar android { ... } block works perfectly for simple projects, as your project grows and you start sharing build logic across multiple modules (e.g., using Convention Plugins), you might find it a bit limiting.

Today, we’ll look at why and how to switch to the more explicit and scalable configure<ApplicationExtension> syntax.

 

🧑🏻‍💻 1. Why Make the Switch?

The standard android { ... } block in build.gradle.kts is actually a "shorthand" provided by the Android Gradle Plugin (AGP). While convenient, using configure<T> offers several advantages:

  • Better Type Safety: By explicitly telling Gradle that "this block is an ApplicationExtension," the IDE (Android Studio) can provide more accurate code completion and error highlighting.
  • Scalable Build Logic: If you are moving common logic into buildSrc or external plugins to keep your Gradle files DRY (Don't Repeat Yourself), using the explicit extension type becomes essential for writing clean, reusable functions.

 

🧑🏻‍💻 2. The Transformation: Before vs. After

Let’s compare the standard approach with the explicit configuration style for an App module.

Before: The Standard android Block


// app/build.gradle.kts
android {
    compileSdk = 35
    defaultConfig {
        applicationId = "com.example.myapp"
        minSdk = 26
        targetSdk = 35
    }
}

After: Using configure<ApplicationExtension>
Note that you will need to import the ApplicationExtension class explicitly.


// app/build.gradle.kts
import com.android.build.api.dsl.ApplicationExtension

configure<ApplicationExtension> {
    compileSdk = 35
    defaultConfig {
        applicationId = "com.example.myapp"
        minSdk = 26
        targetSdk = 35
        // ...
    }
}

 

🧑🏻‍💻 3. Choosing the Right Extension Type

Not every module is an "Application."

You should choose the extension type that matches your module's purpose:

[!TIP]
Use CommonExtension when writing shared logic that applies to both your App and Library modules (like Java versioning or Compose options).

 

🧑🏻‍💻 4. Practical Implementation: Reusable Build Logic

The true power of this syntax shines when you extract common configurations into a function, such as in buildSrc.


// Example of a shared configuration function in buildSrc
import com.android.build.api.dsl.ApplicationExtension
import org.gradle.api.Project

fun Project.configureAndroidApplication() {
    extensions.configure<ApplicationExtension> {
        compileSdk = 35
        defaultConfig {
            minSdk = 26
            // ...other shared settings
        }
    }
}

By defining your build logic this way, your module-level Gradle files stay thin and highly maintainable.

 

🧑🏻‍💻 Conclusion

The traditional android { ... } block is great for its brevity. However, once your project reaches a certain scale and you start treating your build configuration as "real code," switching to configure is the way to go.

It brings better IDE support, type safety, and makes your build logic much easier to share across modules.


Mastering Screen Lifecycle in Jetpack Compose Navigation

When developing with Jetpack Compose, a common challenge is detecting when a screen becomes visible (to refresh data) or when it moves to the background (to pause a video).

While Compose provides onDispose, this only triggers when a Composable is completely removed from the UI tree. It cannot detect when a screen is still in the backstack but no longer visible to the user.

In this post, we’ll explore how to leverage the fact that Navigation Compose uses NavBackStackEntry as a LifecycleOwner to perfectly manage screen-level events.

 

🧑🏻‍💻 1. The Core: Who is the LocalLifecycleOwner?

In Compose, you can access the current lifecycle via LocalLifecycleOwner.current. However, its identity changes depending on your app's architecture:

  • Directly under an Activity: LifecycleOwner = Activity
  • Using Navigation Compose: LifecycleOwner = NavBackStackEntry

When using Navigation Compose, each destination is wrapped in a NavBackStackEntry. When you navigate from Screen A to Screen B, the Activity remains RESUMED, but Screen A’s NavBackStackEntry transitions to the STOPPED state.

By monitoring this, you can capture lifecycle events specific to that individual screen.

 

🧑🏻‍💻 2. The Solution: Implementing ScreenLifecycleObserver

To make this reusable, we can create a custom Composable function that observes these state changes safely.

 

🧑🏻‍💻 3. Real-World Patterns

A. Refreshing Data on Screen Return

Using LaunchedEffect(Unit) only runs once when the screen is first created. If you want to refresh data every time a user navigates back to the screen, use ON_RESUME.

B. Pausing and Resuming Video

Automatically pause video when the user navigates away or minimizes the app, and resume it when they return.

C. Tracking Screen Time (Analytics)

Start a timer on ON_RESUME and send the duration on ON_PAUSE.

 

🧑🏻‍💻 Summary: When to Use What?

Finally, let's distinguish between onDispose and Lifecycle events:

If you are using Navigation Compose, LocalLifecycleOwner.current is a powerful tool. Using it correctly ensures a robust app that respects system resources and provides a seamless user experience.

I hope this guide helps you manage screen lifecycles in your Compose projects!