How does ViewModel work internally in Android SDK?

In Android development, ViewModel is part of the Android Architecture Components and is designed to store and manage UI-related data in a lifecycle-conscious way. This ensures that data survives configuration changes such as screen rotations. ViewModels allow for better separation of concerns, enabling developers to manage and access their data efficiently within Activity and Fragment lifecycles.

Internally, ViewModel works by extending the ViewModel class and is initialized in a way that lifecycle-aware components can access it. The ViewModel is tied to the lifecycle of the activity or fragment, which means it will be retained as long as the scope is valid, allowing data to be preserved across configuration changes.

Here is a simple example to illustrate how to implement a ViewModel in an Android application:

// MyViewModel.java public class MyViewModel extends ViewModel { private MutableLiveData data; public LiveData getData() { if (data == null) { data = new MutableLiveData<>(); loadData(); } return data; } private void loadData() { // Load data logic here (could be from a database or network) data.setValue("Hello, ViewModel!"); } } // MainActivity.java public class MainActivity extends AppCompatActivity { private MyViewModel myViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myViewModel = new ViewModelProvider(this).get(MyViewModel.class); myViewModel.getData().observe(this, new Observer() { @Override public void onChanged(String s) { // Update UI with the data } }); } }

Android ViewModel ViewModel Lifecycle Android Architecture Components Store UI Data Manage UI-related Data