MVVM Architecture for Android Development

Gaya's techtips
2 min readAug 27, 2023

MVVM is model view viewmodel architecture. There are 3 main components. that’s are model,view, viewmodel

model is layer that holds data

view is components that interacts with endusers.

view model holds interaction between view and model with bussiness logics.

personally I look for different examples to learn MVVM architecture for develop android apps. here is structure that I saw in most examples

as I saw MVVM is more friendly to modifications. personally I previously developed android apps from traditional empty layouts and then I moved to react native. Now, I want to learn jetpack compose to develop android apps. this is first step to it.

I create navigator to home screen like below

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ChatWalletTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
val navController = rememberNavController();

NavHost(navController = navController, startDestination = "Home"){
composable("Home"){ HomeScreen(navController = navController)}
composable("Chat"){ ChatScreen()}
}
}
}
}
}
}

Then I create Home Screen View Model Looks Like this

class HomeViewModel : ViewModel(){
private var _uiState = MutableStateFlow(HomeData())
var uiState : StateFlow<HomeData> = _uiState.asStateFlow()

public fun ChangeName() {
_uiState.value = HomeData(UserName = "Hello World!")
}
}

data class HomeData(
var UserName : String = "Rohana"
)

Then I create new UI file like this

@Composable
fun HomeScreen(
homeViewModel: HomeViewModel = viewModel(),
navController: NavController
){
val HomeViewState by homeViewModel.uiState.collectAsState()
Column{
Text(text=HomeViewState.UserName)
Button(onClick={homeViewModel.ChangeName()}){
Text(text="Click Me")
}
}
}

This is very simple example for MVVM Architecture and there are no part of repository. if I add it this note become more complex and this also become more complex like other mvvm architecture tutorials. As first step this is good enoughf idea I think.

--

--