SavedStateEncoderKt

Added in 1.3.0-alpha05

public final class SavedStateEncoderKt


Summary

Public methods

static final @NonNull SavedState
<T extends Object> encodeToSavedState(@NonNull T serializable)

Encode a serializable object to a SavedState with the default serializer.

static final @NonNull SavedState
<T extends Object> encodeToSavedState(
    @NonNull <Error class: unknown class><@NonNull T> serializer,
    @NonNull T value
)

Encode a serializable object to a SavedState with an explicit serializer, which can be a custom or third-party one.

Public methods

encodeToSavedState

public static final @NonNull SavedState <T extends Object> encodeToSavedState(@NonNull T serializable)

Encode a serializable object to a SavedState with the default serializer.

import androidx.savedstate.serialization.encodeToSavedState

class UUIDSerializer : KSerializer<UUID> {
    override val descriptor: SerialDescriptor
        get() = PrimitiveSerialDescriptor("UUIDSerializer", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): UUID {
        return UUID.fromString(decoder.decodeString())
    }

    override fun serialize(encoder: Encoder, value: UUID) {
        encoder.encodeString(value.toString())
    }
}
encodeToSavedState(UUIDSerializer(), UUID.randomUUID())
Parameters
@NonNull T serializable

The serializable object to encode.

Returns
@NonNull SavedState

The encoded SavedState.

Throws
SerializationException

if serializable cannot be serialized.

encodeToSavedState

public static final @NonNull SavedState <T extends Object> encodeToSavedState(
    @NonNull <Error class: unknown class><@NonNull T> serializer,
    @NonNull T value
)

Encode a serializable object to a SavedState with an explicit serializer, which can be a custom or third-party one.

import androidx.savedstate.serialization.encodeToSavedState

@Serializable data class User(val id: Int, val name: String)
val user = User(123, "foo")
val savedState = encodeToSavedState(user)
Parameters
@NonNull <Error class: unknown class><@NonNull T> serializer

The serializer to use.

@NonNull T value

The serializable object to encode.

Returns
@NonNull SavedState

The encoded SavedState.

Throws
SerializationException

if value cannot be serialized.