remember and mutableStateOf

mutableStateOf(v) creates an observable holder: reading it during composition subscribes the reader, and writing it schedules a recomposition. remember { } keeps an object in the composition across recompositions; rememberSaveable also writes it into the saved-state Bundle:

StateDemos.kt: the same counter held two waysKotlin
@Composable
fun CartBadgeDemo(book: Book) {
  LogCompositions("CartBadgeDemo")
  var inMemory by remember { mutableIntStateOf(0) }        // kept in the composition only
  var saved by rememberSaveable { mutableIntStateOf(0) }   // also written to the saved state
  Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
    Text(book.title, style = MaterialTheme.typography.headlineSmall)
    Text("remember: $inMemory in cart", style = MaterialTheme.typography.titleMedium)
    Text("rememberSaveable: $saved in cart", style = MaterialTheme.typography.titleMedium)
    Button(onClick = { inMemory++; saved++ }) { Text("Add to cart") }
  }
}

LogCompositions logs each composition (SideEffect and produceState). Three taps, then a rotation and back:

CartBadgeDemo after three taps, and after a rotation to landscape and back
CartBadgeDemo after three taps, and after a rotation to landscape and back
Output of 87
D/BookNestState: CartBadgeDemo composed #1
...
D/BookNestState: CartBadgeDemo composed #4
D/BookNestLife: onDestroy changing=true
D/BookNestLife: onCreate restored=true
D/BookNestState: CartBadgeDemo composed #1
...

Rotation recreated the composition, so remember restarted at #1 and 0, while rememberSaveable restored 3. Mutate state by assignment: list.add(book) on a list inside mutableStateOf changes nothing Compose 234 can see, so assign a new list or use mutableStateListOf().