State Management in Jetpack Compose

Sep 10 2024 · Kotlin 1.9.22, Android 34, Android Studio Iguana | 2023.2.1 Patch 2

Lesson 05: Saving State

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this demo, you’ll learn how to use the Parcelize interface to be able to add data to the Bundle object. You’ll also see how to create custom rules to save an object.

data class ClubMember(val name: String, val email: String)
var clubMember by rememberSaveable {
    mutableStateOf(ClubMember(name = "", email = ""))
  }
@Composable
fun SignUpScreen(modifier: Modifier = Modifier) {
  var clubMember by rememberSaveable {
    mutableStateOf(ClubMember(name = "", email = ""))
  }
  Column(...) {
    ...
    FieldInputComponent(
      label = "Name",
      inputValue = clubMember.name,
      onInputValueChanged = { newValue ->
        clubMember = clubMember.copy(name = newValue)
      }
    )
    ...
    FieldInputComponent(
      label = "Email",
      inputValue = clubMember.email,
      onInputValueChanged = { newValue ->
        clubMember = clubMember.copy(email = newValue)

      }
    )
  }
}
id 'kotlin-parcelize'
@Parcelize
data class ClubMember(val name: String, val email: String): Parcelable
data class ClubMember(val name: String, val email: String)

val MemberSaver = run {
  val nameKey = "Name"
  val emailKey = "Email"
  mapSaver(
    save = { mapOf(nameKey to it.name, emailKey to it.email) },
    restore = {ClubMember(name = it[nameKey] as String, email = it[emailKey] as String)}
  )
}
var clubMember by rememberSaveable(stateSaver = MemberSaver) {
  mutableStateOf(ClubMember(name = "", email = ""))
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion