기본 Parcelable 레시피

이 레시피에서는 kotlinx.serialization를 사용하지 않고 구성 변경을 유지하는 영구 백 스택을 만드는 기본 예를 보여줍니다. 대신 Android의 Parcelablekotlin-parcelize 플러그인을 사용하여 탐색 상태를 저장하고 복원합니다.

작동 방식

이 예에서 RouteARouteB은 마커 인터페이스 Route를 구현하며, 이는 Parcelable를 확장합니다. 또한 kotlin-parcelize 플러그인에서 @Parcelize로 주석이 달려 있어 Parcelable 구현이 자동으로 생성됩니다.

sealed interface Route : Parcelable

@Parcelize
data object RouteA : Route

@Parcelize
data class RouteB(val id: String) : Route

뒤로 스택을 영구적으로 만들기 위해 이 레시피는 rememberParcelableBackStack 함수를 정의합니다. NavDisplay 및 기타 컴포저블이 뒤로 스택의 변경사항을 인식하도록 뒤로 스택은 SnapshotStateList에 저장됩니다.

@Composable
fun <T : Parcelable> rememberParcelableBackStack(vararg elements: T): SnapshotStateList<T> {
    return rememberSaveable {
        mutableStateListOf(*elements)
    }
}

이는 kotlinx.serialization를 사용하는 androidx.navigation3.runtime의 기본 제공 rememberNavBackStack의 대안으로 작동합니다. 애플리케이션에서 Parcelable를 엄격하게 선호하고 kotlinx.serialization에 의존하지 않는 경우 이 방법을 사용하세요.

/*
 * Copyright 2026 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.nav3recipes.basicparcelable

import android.os.Bundle
import android.os.Parcelable
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.compose.dropUnlessResumed
import androidx.navigation3.runtime.NavEntry
import androidx.navigation3.ui.NavDisplay
import com.example.nav3recipes.content.ContentBlue
import com.example.nav3recipes.content.ContentGreen
import com.example.nav3recipes.ui.setEdgeToEdgeConfig
import kotlinx.parcelize.Parcelize

sealed interface Route : Parcelable

@Parcelize
data object RouteA : Route

@Parcelize
data class RouteB(val id: String) : Route

/**
 * Creates and remembers a [SnapshotStateList] to hold a back stack of [Parcelable] routes
 * that survives configuration changes and process death.
 *
 * @param T The route type, which must implement [Parcelable].
 * @param elements The initial routes to populate the back stack.
 * @return A reactive [SnapshotStateList] managing the navigation back stack.
 */
@Composable
fun <T : Parcelable> rememberParcelableBackStack(vararg elements: T): SnapshotStateList<T> {
    return rememberSaveable {
        mutableStateListOf(*elements)
    }
}

class BasicParcelableActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        setEdgeToEdgeConfig()
        super.onCreate(savedInstanceState)
        setContent {
            val backStack = rememberParcelableBackStack<Route>(RouteA)

            NavDisplay(
                backStack = backStack,
                onBack = { backStack.removeLastOrNull() },
                entryProvider = { key ->
                    when (key) {
                        is RouteA -> NavEntry(key) {
                            ContentGreen("Welcome to Nav3") {
                                Button(onClick = dropUnlessResumed {
                                    backStack.add(RouteB("123"))
                                }) {
                                    Text("Click to navigate")
                                }
                            }
                        }

                        is RouteB -> NavEntry(key) {
                            ContentBlue("Route id: ${key.id} ")
                        }
                    }
                }
            )
        }
    }
}