Android Day 23 MVVM model Intro
MVVM(Model-View-ViewModel)
1.Model: Data and Logic of the App.
2.ViewModel:Handle the logic of Updating the Data.Handle the exposure of the data to the view.
3.View: UI(Composable)
let me show you an simple app that follow the MVVM :
package com.williamjiamin.mvvmdemo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import com.williamjiamin.mvvmdemo.ui.theme.MVVMDemoTheme
import androidx.compose.runtime.livedata.observeAsState
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MVVMDemoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ContactsScreen()
}
}
}
}
}
@Composable
fun ContactsScreen(contactsViewModel: ContactsViewModel = viewModel()) {
val contacts = contactsViewModel.contacts.observeAsState(listOf())
Column {
contacts.value.forEach { contact ->
Text("Name: ${contact.name}, Email: ${contact.email}")
}
Button(onClick = { contactsViewModel.addContact("WilliamJM","WilliamJM@gmail.com") }) {
Text("Add Contact")
}
}
}
This basically give you something like this:
The view model will be :
package com.williamjiamin.mvvmdemo
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class ContactsViewModel : ViewModel() {
private val _contacts = MutableLiveData(listOf(Contact("William Jiamin","WilliamJiamin@gmail.com")))
val contacts: LiveData<List<Contact>> = _contacts
fun addContact(name: String, email: String) {
val updatedList = _contacts.value.orEmpty() + Contact(name, email)
_contacts.value = updatedList
}
}
And the data will be
package com.williamjiamin.mvvmdemo
data class Contact(val name: String, val email: String)