탐색 상태 저장 및 관리
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
다음 섹션에서는 백 스택을 저장하고 백 스택의 항목과 연결된 상태를 저장하는 전략을 설명합니다.
백 스택 저장
우수한 사용자 환경을 제공하려면 구성 변경 및 프로세스 종료와 같은 다양한 수명 주기 이벤트에서 앱의 탐색 상태가 유지되도록 하는 것이 중요합니다. Navigation 3에서는 백 스택을 소유하므로 백 스택을 생성하거나 저장하는 방법에 관한 엄격한 가이드라인이 없습니다. 그러나 Navigation 3에서는 저장 가능한 백 스택을 제공하는 편의 메서드인 rememberNavBackStack
를 제공합니다.
rememberNavBackStack
사용
rememberNavBackStack
컴포저블 함수는 구성 변경 및 프로세스 종료 간에 유지되는 백 스택을 만들도록 설계되었습니다.
rememberNavBackStack
가 올바르게 작동하려면 백 스택의 각 키가 다음과 같은 특정 요구사항을 준수해야 합니다.
NavKey
인터페이스 구현: 백 스택의 모든 키는 NavKey
인터페이스를 구현해야 합니다. 이는 키를 저장할 수 있음을 라이브러리에 알리는 마커 인터페이스 역할을 합니다.
@Serializable
주석이 있음: NavKey
를 구현하는 것 외에도 키 클래스와 객체는 @Serializable
주석으로 표시해야 합니다.
다음 스니펫은 rememberNavBackStack
의 올바른 구현을 보여줍니다.
@Serializable
data object Home : NavKey
@Composable
fun NavBackStack() {
val backStack = rememberNavBackStack(Home)
}
대안: ViewModel
에 저장
백 스택을 관리하는 또 다른 방법은 ViewModel
에 저장하는 것입니다.
ViewModel
또는 기타 맞춤 저장소를 사용할 때 프로세스 종료를 통한 지속성을 보장하려면 다음을 실행해야 합니다.
- 키가 직렬화 가능해야 함:
rememberNavBackStack
와 마찬가지로 탐색 키는 직렬화 가능해야 합니다.
- 직렬화 및 역직렬화를 수동으로 처리: 각 키의 직렬화된 표현을 영구 저장소 (예:
SharedPreferences
, 데이터베이스 또는 파일)을 저장합니다.
ViewModel
를 NavEntry
로 범위 지정
ViewModels
는 화면 회전과 같은 구성 변경 전반에서 UI 관련 상태를 유지하는 데 사용됩니다. 기본적으로 ViewModels
의 범위는 가장 가까운 ViewModelStoreOwner
(일반적으로 Activity
또는 Fragment
)로 설정됩니다.
하지만 ViewModel
의 범위를 전체 Activity
가 아닌 백 스택의 특정 NavEntry
(예: 특정 화면 또는 대상)로 지정하는 것이 좋습니다. 이렇게 하면 특정 NavEntry
가 백 스택에 있는 동안만 ViewModel
의 상태가 유지되고 NavEntry
가 팝되면 삭제됩니다.
androidx.lifecycle:lifecycle-viewmodel-navigation3
부가기능 라이브러리는 이를 용이하게 하는 NavEntryDecorator
를 제공합니다. 이 데코레이터는 각 NavEntry
에 ViewModelStoreOwner
를 제공합니다. NavEntry
의 콘텐츠 내에 ViewModel
를 만들면 (예: Compose에서 viewModel()
사용) 백 스택의 해당 NavEntry
키로 자동으로 범위가 지정됩니다. 즉, NavEntry
가 백 스택에 추가될 때 ViewModel
이 생성되고 삭제될 때 삭제됩니다.
ViewModel
를 NavEntry
로 범위 지정하는 데 NavEntryDecorator
를 사용하려면 다음 단계를 따르세요.
androidx.lifecycle:lifecycle-viewmodel-navigation3
종속 항목을 app/build.gradle.kts
파일에 추가합니다.
NavDisplay
를 구성할 때 entryDecorators
목록에 rememberSavedStateNavEntryDecorator()
를 추가합니다.
NavDisplay
에 다른 데코레이터를 추가합니다.
NavDisplay(
entryDecorators = listOf(
// Add the default decorators for managing scenes and saving state
rememberSceneSetupNavEntryDecorator(),
rememberSavedStateNavEntryDecorator(),
// Then add the view model store decorator
rememberViewModelStoreNavEntryDecorator()
),
backStack = backStack,
entryProvider = entryProvider { },
)
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Save and manage navigation state\n\nThe following sections describe strategies for saving your back stack and\nstoring state associated with entries on your back stack.\n\nSave your back stack\n--------------------\n\nEnsuring your app's navigation state persists across various lifecycle events,\nincluding configuration changes and process death, is crucial for a good user\nexperience. In Navigation 3, you own your back stack, so there aren't strict\nguidelines on how you should create or save it. However, Navigation 3 does offer\na convenience method that provides you with a saveable back stack:\n[`rememberNavBackStack`](/reference/kotlin/androidx/navigation3/runtime/package-summary#rememberNavBackStack(kotlin.Array)).\n\n### Use `rememberNavBackStack`\n\nThe `rememberNavBackStack` composable function is designed to create a back\nstack that persists across configuration changes and process death.\n\nFor `rememberNavBackStack` to function correctly, each key in your back stack\nmust adhere to specific requirements:\n\n- **Implement `NavKey` interface** : Every key in the back stack must implement the [`NavKey`](/reference/kotlin/androidx/navigation3/runtime/NavKey) interface. This acts as a marker interface that signals to the library that the key can be saved.\n- **Have the `@Serializable` annotation** : In addition to implementing `NavKey`, your key classes and objects must be marked with the `@Serializable` annotation.\n\nThe following snippet shows a correct implementation of `rememberNavBackStack`:\n\n\n```kotlin\n@Serializable\ndata object Home : NavKey\n\n@Composable\nfun NavBackStack() {\n val backStack = rememberNavBackStack(Home)\n}https://github.com/android/snippets/blob/26d364466ee1c03d658ba2f0905f7cc1a97afefa/compose/snippets/src/main/java/com/example/compose/snippets/navigation3/savingstate/SavingStateSnippets.kt#L30-L36\n```\n\n\u003cbr /\u003e\n\n### Alternative: Storing in a `ViewModel`\n\nAnother approach to managing your back stack is to store it in a `ViewModel`.\nFor persistence through process death when using a `ViewModel` or any other\ncustom storage, you need to:\n\n- **Ensure your keys are serializable** : Just like with `rememberNavBackStack`, your navigation keys must be serializable.\n- **Handle serialization and deserialization manually** : You're responsible for manually saving the serialized representation of each key to, and deserializing it from, persistent storage (e.g., `SharedPreferences`, a database, or a file) when your app is going into the background or being restored.\n\nScoping `ViewModel`s to `NavEntry`s\n-----------------------------------\n\n`ViewModels` are used to retain UI-related state across configuration changes,\nsuch as screen rotations. By default, `ViewModels` are scoped to the nearest\n`ViewModelStoreOwner`, which is typically your `Activity` or `Fragment`.\n\nHowever, you might want to scope a `ViewModel` to a specific `NavEntry` (i.e., a\nspecific screen or destination) on the back stack, rather than the entire\n`Activity`. This ensures that the `ViewModel`'s state is retained only while\nthat particular `NavEntry` is part of the back stack, and is cleared when the\n`NavEntry` is popped.\n\nThe `androidx.lifecycle:lifecycle-viewmodel-navigation3` add-on library provides\na `NavEntryDecorator` that facilitates this. This decorator provides a\n`ViewModelStoreOwner` for each `NavEntry`. When you create a `ViewModel` inside a\n`NavEntry`'s content (e.g., using `viewModel()` in Compose), it is automatically\nscoped to that specific `NavEntry`'s key on the back stack. This means the\n`ViewModel` is created when the `NavEntry` is added to the back stack, and\ncleared when it's removed.\n\nTo use `NavEntryDecorator` for scoping `ViewModel`s to `NavEntry`s, follow these\nsteps:\n\n1. Add the `androidx.lifecycle:lifecycle-viewmodel-navigation3` dependency to your `app/build.gradle.kts` file.\n2. Add [`rememberSavedStateNavEntryDecorator()`](/reference/kotlin/androidx/navigation3/runtime/package-summary#rememberSavedStateNavEntryDecorator(androidx.compose.runtime.saveable.SaveableStateHolder)) to the list of `entryDecorators` when constructing a `NavDisplay`.\n3. Add other decorators into your `NavDisplay`.\n\n\n```kotlin\nNavDisplay(\n entryDecorators = listOf(\n // Add the default decorators for managing scenes and saving state\n rememberSceneSetupNavEntryDecorator(),\n rememberSavedStateNavEntryDecorator(),\n // Then add the view model store decorator\n rememberViewModelStoreNavEntryDecorator()\n ),\n backStack = backStack,\n entryProvider = entryProvider { },\n)https://github.com/android/snippets/blob/26d364466ee1c03d658ba2f0905f7cc1a97afefa/compose/snippets/src/main/java/com/example/compose/snippets/navigation3/savingstate/SavingStateSnippets.kt#L45-L55\n```\n\n\u003cbr /\u003e"]]