Sobes.tech
Middle

Tell us about the MVVM pattern and its application in Android app development.

sobes.tech AI

Answer from AI

MVVM (Model-View-ViewModel) is an architectural pattern that divides an application into three interconnected components:

  • Model: Represents data and business logic. Usually, these are classes working with databases, network requests, etc.
  • View: Displays data and interacts with the user. These are activities, fragments, user interface (UI) elements. The View does not contain data processing logic.
  • ViewModel: Acts as an intermediary between the Model and the View. It contains data ready for display in the View and handles user actions, delegating them to the Model. The ViewModel does not directly know about the View, making it independent of the UI lifecycle.

Application in Android:

The ViewModel stores UI-related data in such a way that it survives configuration changes (e.g., screen rotation). Android Architecture Components provide the ViewModel class. The View (activity or fragment) observes data in the ViewModel using LiveData. When data changes in the ViewModel, LiveData notifies the View, which then updates the UI.

Advantages of MVVM in Android:

  • Testability: ViewModel is easy to test in isolation because it does not depend on Android UI classes.
  • Lifecycle support: ViewModel survives configuration changes, preventing data loss.
  • Separation of concerns: Clear separation between UI, presentation logic, and data.
  • Reduction of boilerplate code: Using LiveData and data binding simplifies UI updates.

Example of using LiveData and ViewModel:

// ViewModel
class MyViewModel : ViewModel() {
    private val _data = MutableLiveData<String>()
    val data: LiveData<String> = _data // Public LiveData for observation

    fun fetchData() {
        // Simulate data retrieval
        _data.value = "Data loaded!"
    }
}
// View (Activity or Fragment)
class MyActivity : AppCompatActivity() {

    private lateinit var viewModel: MyViewModel

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

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

        // Observe LiveData
        viewModel.data.observe(this, Observer { newData ->
            // Update UI on data change
            textView.text = newData
        })

        // Call ViewModel method
        button.setOnClickListener {
            viewModel.fetchData()
        }
    }
}