Skip to content
This repository has been archived by the owner on Mar 2, 2024. It is now read-only.

cheonjaeung/savedstate-ktx

Repository files navigation

SavedState KTX

android-sdk kotlin-version maven-central license test

SavedState-KTX is an Android library that contains Kotlin extensions for SavedStateHandle.

Installation

dependencies {
    implementation "io.woong.savedstate:savedstate-ktx:1.2.0"
}

Add dependency to build.gradle in your android project.

Usage

Delegated Property

This library provides useful extensions for creating delegated properties. You can save a value to SavedStateHandle via property. In same way, you can get a value from SavedStateHandle via property.

All delegated things can used via by keyword of Kotlin. For more information about Kotlin's delegation, see official documentations. (About delegation & delegated properties)

class SampleViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    var property1: String? by savedStateHandle.nullable()
    var property2: String? by savedStateHandle.nullable("foo")
    var property3: String by savedStateHandle.notNull("bar")
}

You can create delegated properties like above sample code. Delegated properties can divided into 2 types, nullable and not null.

Nullable property can be used by nullable function. It has optional parameter, initial value. If initial value is not set, the property will contains null at initial.

Not null property can be used by notNull function. notNull must have one initial value.

Delegated LiveData

class SampleViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val _liveData: MutableLiveData<String> by savedStateHandle.liveData()
    val liveData: LiveData<String>
        get() = _liveData
}

You can create delegated livedata like sample. Delegated livedata stores value in the SavedStateHandle like delegated properties.

Delegated StateFlow

class SampleViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    val stateFlow: StateFlow<String> by savedStateHandle.stateFlow("init")
}

Like delegated livedata, you can use delegated stateflow like this.

class SampleViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    @OptIn(ExperimentalSavedStateKtxApi::class)
    val stateFlow: MutableStateFlow<String> by savedStateHandle.mutableStateFlow("init")
}

Delegated mutable stateflow is currently experimental feature. You can use like above sample.

License

SavedState KTX is under the MIT License.

About

Simple Kotlin library that provides simple and useful extensions for Android SavedStateHandle.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages