What is MVVM in Jetpack Compose?
- User
What is MVVM in Jetpack Compose?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
What is MVVM in Jetpack Compose?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
MVVM (Model-View-ViewModel) is a design pattern commonly used in Android development to separate the concerns of an application into three main components: the Model, the View, and the ViewModel. When applied to Jetpack Compose, MVVM helps in creating a clean and maintainable architecture for building UI components.
Here's a breakdown of each component in the context of Jetpack Compose:
Model:
View:
ViewModel:
Here's a simple example to illustrate the MVVM pattern in Jetpack Compose:
data class User(val name: String, val age: Int)
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class UserViewModel : ViewModel() {
private val _user = MutableStateFlow<User?>(null)
val user: StateFlow<User?> = _user
fun fetchUser() {
viewModelScope.launch {
// Simulate a network call or database fetch
val fetchedUser = User("John Doe", 30)
_user.value = fetchedUser
}
}
}
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun UserScreen(viewModel: UserViewModel = viewModel()) {
val user by viewModel.user.collectAsState()
LaunchedEffect(Unit) {
viewModel.fetchUser()
}
if (user != null) {
Text(text = "Name: ${user?.name}, Age: ${user?.age}")
} else {
CircularProgressIndicator()
}
}
@Preview(showBackground = true)
@Composable
fun PreviewUserScreen() {
UserScreen()
}
StateFlow or LiveData) to manage the state of the UI.By following the MVVM pattern in Jetpack Compose, you can create a more modular, testable, and maintainable codebase.