Compose Part 1
Q1. Explain the difference between remember and rememberSaveable and when each is appropriate.
remember and rememberSaveable and when each is appropriate.@Composable
fun LoginForm() {
// Lost on rotation / process death
var username by remember { mutableStateOf("") }
// Survives rotation and process death
var password by rememberSaveable { mutableStateOf("") }
// Custom Saver for a non-Bundle type
data class User(val name: String, val age: Int)
val userSaver = Saver<User, List<<Any>>(
save = { listOf(it.name, it.age) },
restore = { User(it[0] as String, it[1] as Int) }
)
var user by rememberSaveable(stateSaver = userSaver) { mutableStateOf(User("Alex", 25)) }
OutlinedTextField(value = username, onValueChange = { username = it }, label = { Text("Username") })
OutlinedTextField(value = password, onValueChange = { password = it }, label = { Text("Password") })
}Q2. What triggers recomposition in Compose, and how does the compiler optimize it via stability inference?
Q3. How do @Stable, @Immutable, and @NonRestartableComposable annotations affect recomposition behavior?
@Stable, @Immutable, and @NonRestartableComposable annotations affect recomposition behavior?Q4. Why is it problematic to pass unstable types (e.g., ArrayList, ViewModel) directly into Composable parameters?
ArrayList, ViewModel) directly into Composable parameters?Q5. What is the role of SnapshotState and how does it integrate with Compose's observation system?
SnapshotState and how does it integrate with Compose's observation system?Q6. Explain the difference between derivedStateOf and remember(key) — when would you choose one over the other?
derivedStateOf and remember(key) — when would you choose one over the other?Q7. What happens if you write var text by remember { mutableStateOf("") } inside a Composable versus hoisting it to a ViewModel?
var text by remember { mutableStateOf("") } inside a Composable versus hoisting it to a ViewModel?Q8. How do you implement unidirectional data flow in a Compose-heavy application?
Q9. What are the trade-offs between ViewModel state holders versus plain class state holders in Compose?
ViewModel state holders versus plain class state holders in Compose?Q10. How do you handle configuration changes (e.g., rotation) with Compose state without relying on ViewModel?
ViewModel?Last updated