Sobes.tech
Junior

Tell me about Jetpack ViewModel.

sobes.tech AI

Answer from AI

The ViewModel stores and manages UI-related data considering the lifecycle. It survives configuration changes (screen rotations, layout changes), preventing data loss.

Key features:

  • Data preservation: ViewModel is not destroyed during configuration changes, maintaining UI state.
  • Separation of logic from UI: Business logic is placed in ViewModel, simplifying testing and support for Activity/Fragment.
  • Integration with LiveData: Often used with LiveData to observe data changes.

Example usage:

// MyViewModel.kt
import androidx.lifecycle.ViewModel

class MyViewModel : ViewModel() {
    // Data to be preserved during configuration changes
    var counter = 0
}
// MyActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider

class MyActivity : AppCompatActivity() {
    private lateinit var viewModel: MyViewModel
    private lateinit var counterText: TextView
    private lateinit var incrementButton: Button

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

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

        counterText = findViewById(R.id.counter_text)
        incrementButton = findViewById(R.id.increment_button)

        // Display data from ViewModel
        updateCounterDisplay()

        incrementButton.setOnClickListener {
            viewModel.counter++
            updateCounterDisplay()
        }
    }

    private fun updateCounterDisplay() {
        counterText.text = viewModel.counter.toString()
    }
}

Lifecycle: ViewModel lives as long as the associated Scope (e.g., Activity) is alive. When the Scope ends, the ViewModel is destroyed.

ViewModelProviders (now ViewModelProvider) was used to obtain a ViewModel instance before Kotlin. In Kotlin, it is recommended to use ViewModelProvider(this).get(MyViewModel::class.java).

Main advantages of ViewModel over regular classes for storing UI state:

  • Survives configuration changes.
  • Managed by the Jetpack lifecycle framework.

Disadvantages:

  • Can become too large with complex UI logic.
  • Should not contain references to Views, Context, or other lifecycle-bound objects to avoid memory leaks.
Tell me about Jetpack ViewModel. — Android - sobes.tech