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

--

--

--

“An idiot admires complexity. A genius admires simplicity.” — Terry A Davis

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Developing a Todo app with android integration testing following TDD approach — Part 3 of 3

Demystifying RowsSupportFragment and BrowseSupportFragment

Parallel Test For UI Automation With Fladle

Tips to keep your android project files and code organized

Stutern Android Take Home Task

Flutter Windows executable creation

Creating Custom Views in Android

90 Days Of Greatness: Week 1 — All about Activities and Intents

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
Ezra Lazuardy

Ezra Lazuardy

“An idiot admires complexity. A genius admires simplicity.” — Terry A Davis

More from Medium

Wireless Debugging — Android Apps

Android Jetpack Compose —  Basic

Android guide: Service

Android WorkManager