How to migrate to ViewModel from an older API?

As Android development evolves, migrating to ViewModel from older APIs offers a cleaner architecture by separating UI-related data from the Activity/Fragment lifecycle. This ensures that data survives configuration changes like screen rotations, providing a smoother user experience.

Migration Steps

  1. Identify the existing data source currently managed in your Activity/Fragment.
  2. Create a ViewModel class that will hold the data.
  3. Update the Activity/Fragment to use the ViewModel.
  4. Implement LiveData to observe data changes.

Example

// ViewModel Class 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 here data.setValue("Hello, ViewModel!"); } } // In your Activity/Fragment public class MyActivity extends AppCompatActivity { private MyViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); viewModel = new ViewModelProvider(this).get(MyViewModel.class); viewModel.getData().observe(this, newData -> { // Update UI with new data textView.setText(newData); }); } }

ViewModel Android LiveData MVVM architecture migration AndroidX