0 votes
in Android Library by
Can you explain the role of the Android ViewModel and how it helps in maintaining state across configuration changes?

1 Answer

0 votes
by
The Android ViewModel plays a crucial role in maintaining state across configuration changes, such as screen rotations. It is part of the Architecture Components library and designed to store UI-related data separate from the Activity or Fragment lifecycle.

ViewModels survive configuration changes by being scoped to the lifecycle of an Activity or Fragment’s view hierarchy rather than their instances. This allows them to retain data during events like screen rotation, preventing unnecessary data reloading and improving app performance.

To use a ViewModel, create a class extending ViewModel, then instantiate it using ViewModelProvider within the associated Activity or Fragment. Store any UI-related data inside the ViewModel, observing LiveData objects for updates when necessary.

For example:

class MyViewModel : ViewModel() {

    private val _data = MutableLiveData<String>()

    val data: LiveData<String> get() = _data

    fun loadData() { /* ... */ }

}

class MyFragment : Fragment() {

    private lateinit var viewModel: MyViewModel

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)

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

        viewModel.data.observe(viewLifecycleOwner, Observer { /* Update UI */ })

    }

}
...