Skip to content

Commit

Permalink
Described state preservation of a retained instance in the docs
Browse files Browse the repository at this point in the history
  • Loading branch information
arkivanov committed Sep 8, 2023
1 parent 1f0f04a commit 91511a3
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions docs/component/state-preservation.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,45 @@ Sometimes it might be necessary to preserve state or data in a component when it

The `decompose` module adds Essenty's `state-keeper` module as `api` dependency, so you don't need to explicitly add it to your project. Please familiarise yourself with Essenty library, especially with the `StateKeeper`.

## Usage example
## Usage examples

```kotlin
import com.arkivanov.decompose.ComponentContext
```kotlin title="Saving state in a component"
import com.arkivanov.essenty.instancekeeper.InstanceKeeper
import com.arkivanov.essenty.instancekeeper.getOrCreate
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.ParcelableContainer
import com.arkivanov.essenty.parcelable.Parcelize
import com.arkivanov.essenty.parcelable.consume
import com.arkivanov.essenty.statekeeper.consume

class SomeComponent(
componentContext: ComponentContext
) : ComponentContext by componentContext {

private var state: State = stateKeeper.consume(key = "SAVED_STATE") ?: State()
private val statefulEntity =
instanceKeeper.getOrCreate {
SomeStatefulEntity(savedState = stateKeeper.consume(key = "SAVED_STATE"))
}

init {
stateKeeper.register(key = "SAVED_STATE") { state }
stateKeeper.register(key = "SAVED_STATE", supplier = statefulEntity::saveState)
}
}

class SomeStatefulEntity(
savedState: ParcelableContainer?,
) : InstanceKeeper.Instance {

var state: State = savedState?.consume() ?: State()
private set

fun saveState(): ParcelableContainer =
ParcelableContainer(state)

override fun onDestroy() {}

@Parcelize
private class State(val someValue: Int = 0) : Parcelable
data class State(val someValue: Int = 0) : Parcelable
}
```

Expand Down

0 comments on commit 91511a3

Please sign in to comment.