androidx.navigation3.runtime.serialization


Classes

NavBackStackSerializer

A KSerializer for NavBackStack.

Cmn
NavKeySerializer

A KSerializer for handling polymorphic NavKey hierarchies on Android.

android

Top-level functions summary

inline NavBackStackSerializer<T>

Creates a NavBackStackSerializer for a polymorphic NavKey base type.

Cmn

Top-level functions

inline fun <T : NavKey> NavBackStackSerializer(): NavBackStackSerializer<T>

Creates a NavBackStackSerializer for a polymorphic NavKey base type.

This factory function is a convenience for creating a serializer for a NavBackStack whose elements are polymorphic (e.g., different implementations of a NavKey interface).

It retrieves a base serializer for the element type T (which is typically the base NavKey interface).

Important: For polymorphic serialization to work, you must provide a SerializersModule (containing all concrete NavKey subtypes) to your Encoder/Decoder (e.g., via rememberSerializable).

kotlinx.serialization's polymorphic dispatch relies on the module available during the encoding/decoding process, not on the specific serializer retrieved by this function.

import androidx.navigation3.runtime.NavBackStack
import androidx.navigation3.runtime.samples.RememberNavBackStackSamples.Details
import androidx.navigation3.runtime.samples.RememberNavBackStackSamples.Home
import androidx.navigation3.runtime.samples.RememberNavBackStackSamples.Screen
import androidx.navigation3.runtime.serialization.NavBackStackSerializer
import androidx.savedstate.serialization.SavedStateConfiguration
import androidx.savedstate.serialization.decodeFromSavedState
import androidx.savedstate.serialization.encodeToSavedState

val module = SerializersModule {
    polymorphic(Screen::class) {
        subclass(Home.serializer())
        subclass(Details.serializer())
    }
}
val configuration = SavedStateConfiguration { serializersModule = module }

val serializer = NavBackStackSerializer<Screen>()

// Pass the same configuration (or at least its serializersModule) to encode/decode:
val backStack = NavBackStack(Home("abc"), Details(42))
val encoded = encodeToSavedState(serializer, backStack, configuration)
val decoded = decodeFromSavedState(serializer, encoded, configuration)
Parameters
<T : NavKey>

The reified element type, typically the base NavKey interface.

Returns
NavBackStackSerializer<T>

A new NavBackStackSerializer configured for the base polymorphic type.