SoFunction
Updated on 2025-03-11

Deeply understand and run the ViewModel of Android Jetpack components

What is ViewModel

ViewModel is one of the Android Jetpack components. Its main purpose is to separate UI controllers (such as Activity and Fragment) from data-related business logic, so that UI controllers can focus on displaying data and responding to user interactions, while data acquisition and processing are managed by ViewModel. This separation makes the code clearer, easier to test and maintain.

The principle of ViewModel

The principle of ViewModel is actually not complicated. When device configuration changes (such as screen rotation) causes the Activity or Fragment to be rebuilt, the ViewModel is not destroyed but is retained in memory. In this way, the UI controller can re-acquire the previous ViewModel instance after reconstruction and continue to use the data in it, thereby avoiding data loss and duplicate loading.

ViewModelStore and ViewModelStoreOwner

The principle of ViewModel involves two core concepts: ViewModelStore and ViewModelStoreOwner.

ViewModelStore is a container that stores ViewModel instances, and its life cycle is associated with the life cycle of the UI controller. When the UI controller (Activity or Fragment) is destroyed, the ViewModelStore will clean up the ViewModel instances in it to avoid memory leaks.

ViewModelStoreOwner is an object that owns the ViewModelStore, usually an Activity or Fragment. ViewModelProvider obtains ViewModelStore through ViewModelStoreOwner, and manages the life cycle of ViewModel through ViewModelStore.

ViewModelProvider

ViewModelProvider is a tool class for creating and getting ViewModel instances. It is responsible for associating the ViewModel with the ViewModelStoreOwner and ensuring that the ViewModel is destroyed at the right time.

Get the ViewModel instance in Activity:

viewModel = new ViewModelProvider(this).get();

Get the ViewModel instance in Fragment:

viewModel = new ViewModelProvider(this).get();

Using ViewModel

Add ViewModel dependencies

First, make sure your project has AndroidX already and add ViewModel dependencies in it:

dependencies {
    implementation ":lifecycle-viewmodel-ktx:2.3.1"
}

Create ViewModel

Creating a ViewModel is very simple, just inherit the ViewModel class and define data and related operations there.

public class MyViewModel extends ViewModel {
    private MutableLiveData<String> data = new MutableLiveData<>();
    public LiveData<String> getData() {
        return data;
    }
    public void fetchData() {
        // Simulate asynchronous data acquisition        new Handler().postDelayed(() -> {
            ("Hello, ViewModel!");
        }, 2000);
    }
}

Using ViewModel in UI Controller

Get an instance of ViewModel in Activity or Fragment and observe the data changes:

viewModel = new ViewModelProvider(this).get();
().observe(this, data -> {
    // Update the UI    (data);
});
(); // Trigger data acquisition operation

ViewModel communicates with cross-components

ViewModel is not only used to share data inside a single UI controller, it can also be used to share data between different UI controllers, enabling cross-component communication. For example, data in a Fragment can be passed to the Activity through a ViewModel.

Share data in Activity:

sharedViewModel = new ViewModelProvider(this).get();
().observe(this, data -> {
    // Update the UI    (data);
});

Share data in a Fragment:

sharedViewModel = new ViewModelProvider(requireActivity()).get();

Note: When communicating across components, you need to use the same ViewModelProvider to get the same type of ViewModel instance. In Activity, use this as the parameter of ViewModelProvider, and in Fragment, use requireActivity() as the parameter.

ViewModel and SavedState

Sometimes, we may want to save some data in the ViewModel that is independent of the UI controller lifecycle in order to restore state at rebuild time. ViewModel provides SavedState function, which allows us to persist data in ViewModel.

Sample code:

public class MyViewModel extends ViewModel {
    private SavedStateHandle savedStateHandle;
    public MyViewModel(SavedStateHandle savedStateHandle) {
         = savedStateHandle;
    }
    public LiveData<String> getData() {
        return ("data");
    }
    public void setData(String data) {
        ("data", data);
    }
}

Create a ViewModel with SavedState function using SavedStateViewModelFactory:

public class MyActivity extends AppCompatActivity {
    private MyViewModel viewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        setContentView(.activity_main);
         factory = new SavedStateViewModelFactory(getApplication(), this);
        viewModel = new ViewModelProvider(this, factory).get();
        ().observe(this, data -&gt; {
            // Update the UI            (data);
        });
        if (savedInstanceState == null) {
            // When the first creation is created, the data acquisition operation is triggered            ();
        }
    }
}

Points to note during the use of ViewModel

  • Do not hold a reference to the Context in the ViewModel to avoid throwing memory leaks.
  • ViewModel should only focus on data and business logic and should not handle UI-related operations.
  • Do not save a lot of data in the ViewModel to avoid taking up too much memory.
  • When the amount of data is large or requires sharing data across processes, you should consider using other solutions such as Room databases or SharedPreferences.

in conclusion

Through the introduction of this article, you have already understood the use and principles of Android Jetpack ViewModel. The emergence of ViewModel has greatly simplified data management and lifecycle processing in Android development, making applications more robust and efficient. In actual development, the rational use of ViewModel can help you build elegant and easy-to-maintain Android applications.

The above is the detailed content of the ViewModel in-depth understanding and running Android Jetpack components. For more information about Android Jetpack ViewModel, please follow my other related articles!