androidengineers.Book a session
โ† All interview questions
Jetpack ComposeIntermediate2 min

Inserting a lesson moves an expanded row to the wrong item. What is missing?

Answer

A list position is not a lesson identity. When a new lesson is inserted at the top, every later position shifts. Without explicit item keys, locally remembered expansion state can be associated with the wrong lesson.

Example

Assume each lesson has a unique, stable string id:

LazyColumn {
    items(lessons, key = { lesson -> lesson.id }) { lesson ->
        var expanded by rememberSaveable { mutableStateOf(false) }

        Column {
            TextButton(onClick = { expanded = !expanded }) {
                Text(lesson.title)
            }
            if (expanded) {
                Text(lesson.summary)
            }
        }
    }
}

Use an ID from the domain model, not a random value generated during composition. Choose a key type supported by saved state when using rememberSaveable inside an item.

Trade-off

If multiple screens need the expansion selection, or only one row may be expanded, hoist the selected ID to a shared state owner. Stable keys solve item identity; they do not decide where product state belongs.

Follow-up to practise

Would contentType fix this? No. Content types help reuse compatible item compositions, such as header versus lesson layouts. Keys identify individual items. Test insertion, reordering, deletion, and duplicate IDs separately.

Reference

Android Developers: Lazy lists and grids

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising