0
0
Android Kotlinmobile~7 mins

MVVM pattern in Android Kotlin

Choose your learning style9 modes available
Introduction

The MVVM pattern helps organize your app code by separating the user interface from the data and logic. This makes your app easier to build, test, and maintain.

When building an app with complex user interactions and data updates.
When you want to keep your UI code simple and free from business logic.
When you want to easily test your app's logic without the UI.
When you want to update the UI automatically when data changes.
When working in a team where designers and developers work separately.
Syntax
Android Kotlin
class MyViewModel : ViewModel() {
    val data = MutableLiveData<String>()

    fun updateData(newData: String) {
        data.value = newData
    }
}

// In Activity or Fragment
myViewModel.data.observe(this) { updatedData ->
    textView.text = updatedData
}

ViewModel holds and manages UI-related data.

LiveData is used to observe data changes and update the UI automatically.

Examples
This ViewModel holds a message string that the UI can observe and update.
Android Kotlin
class MyViewModel : ViewModel() {
    val message = MutableLiveData<String>()

    fun setMessage(text: String) {
        message.value = text
    }
}
The UI observes the message LiveData and updates the TextView when the message changes.
Android Kotlin
viewModel.message.observe(this) { newMessage ->
    textView.text = newMessage
}
Sample App

This app has a button and a text view. When you tap the button, the ViewModel updates the greeting message. The text view automatically shows the new message thanks to LiveData observation.

Android Kotlin
class MainViewModel : ViewModel() {
    val greeting = MutableLiveData<String>()

    fun sayHello() {
        greeting.value = "Hello, MVVM!"
    }
}

class MainActivity : AppCompatActivity() {
    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        val textView = findViewById<TextView>(R.id.textView)
        val button = findViewById<Button>(R.id.button)

        viewModel.greeting.observe(this) { message ->
            textView.text = message
        }

        button.setOnClickListener {
            viewModel.sayHello()
        }
    }
}
OutputSuccess
Important Notes

Always keep UI code in Activities or Fragments simple and free from data logic.

Use LiveData to automatically update the UI when data changes.

ViewModel survives configuration changes like screen rotations, keeping your data safe.

Summary

MVVM separates UI (View), data logic (ViewModel), and data (Model).

ViewModel holds data and exposes it via LiveData for the UI to observe.

This pattern makes apps easier to maintain and test.