Android ❤️ MVVM

Photo by Mark Boss on Unsplash

The MVVM Architecture

Source: Wikipedia

View

View Model

Model

How we apply it to Android?

// Lifecycle Extensions
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
data class User (
val name: String
)
class MainViewModel : ViewModel() {    val user = liveData {
emit(User(name = "Ezra Lazuardy"))
}
}
class MainActivity : AppCompatActivity() {    // use the View Model    
private val mainViewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// observe the Live Data in View Model
mainViewModel.user.observe(this, Observer { user ->
// set the Text View's text
text_view.text = user.name
})
}
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store