Instruction

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

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

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

Unlock now

Data types that can be added to a Bundle object include primitives, like Int, or small, simple objects, like String. In an Android app, you’ll have not only primitives or Strings but also more complex data types. For example, storing a user profile in a data class:

data class UserProfile(val name: String, val nickName: String, val age: Int)

To add a UserProfile object to a Bundle, you must make the UserProfile object parcelable. To achieve this, you add the @Parcelize annotation to the UserProfile data class:

@Parcelize
data class UserUserProfile(val name: String, val nickName: String, val age: Int): Parcelable

Then you save a UserProfile in a composable function like this:

@Composable
fun UserProfileScreen(){
  val userProfile by rememberSaveable {
    mutableStateOf(UserProfile(name = "Bilbo Baggins", nickName = "Bilbo", age = 131))
  }
    ...
}

If you can’t use the Parcelize interface to save the state, you can create a custom saver object using either mapSaver or listSaver functions. These functions let you define your own rules that will convert an object to a set of values that can be added to the Bundle object.

You’d use the mapSaver function to represent your class as a map of values that can be saved individually. The listSaver function lets you represent your class as a list of values.

Here’s an example of saving a UserProfile object using the listSaver function:

data class UserProfile(val name: String, val nickName: String, val age: Int)

// 1
val ProfileSaver = listSaver<UserProfile, Any>(
  // 2
  save = { listOf(it.name, it.nickName, it.age) },
  // 3
  restore = { UserProfile(name = it[0] as String, nickName = it[1] as String, age = it[2] as Int) }
)

In the code above:

  1. You create a ProfileSaver object using the listSaver function.
  2. The save lambda converts the UserProfile object to a list of items that will be added to the Bundle object individually.
  3. The restore lambda creates a UserProfile object from the list of items.

Then you use the saver to save a UserProfile object across configuration changes like this:

@Composable
fun UserProfileScreen() {
  val userProfile by rememberSaveable(stateSaver = ProfileSaver) {
    mutableStateOf(UserProfile(name = "Bilbo Baggins", nickName = "Bilbo", age = 131))
  }
}

Now, you’ll create a custom object using the mapSaver function in a demo.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo