public abstract class ViewModel

Known direct subclasses
AndroidViewModel

Application context aware ViewModel.


ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

A ViewModel is always created in association with a scope (a fragment or an activity) and will be retained as long as the scope is alive. E.g. if it is an Activity, until it is finished.

In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new owner instance just re-connects to the existing model.

The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment. The Activity or the Fragment should be able to observe changes in the ViewModel. ViewModels usually expose this information via LiveData or Android Data Binding. You can also use any observability construct from your favorite framework.

ViewModel's only responsibility is to manage the data for the UI. It should never access your view hierarchy or hold a reference back to the Activity or the Fragment.

Typical usage from an Activity standpoint would be:

public class UserActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_activity_layout);
        final UserModel viewModel = new ViewModelProvider(this).get(UserModel.class);
        viewModel.getUser().observe(this, new Observer<User>() {
            @Override
            public void onChanged(@Nullable User data) {
                // update ui.
            }
        });
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 viewModel.doAction();
            }
        });
    }
}
ViewModel would be:
public class UserModel extends ViewModel {
    private final MutableLiveData<User> userLiveData = new MutableLiveData<>();

    public LiveData<User> getUser() {
        return userLiveData;
    }

    public UserModel() {
        // trigger user load.
    }

    void doAction() {
        // depending on the action, do necessary business logic calls and update the
        // userLiveData.
    }
}

ViewModels can also be used as a communication layer between different Fragments of an Activity. Each Fragment can acquire the ViewModel using the same key via their Activity. This allows communication between Fragments in a de-coupled fashion such that they never need to talk to the other Fragment directly.

public class MyFragment extends Fragment {
    public void onStart() {
        UserModel userModel = new ViewModelProvider(requireActivity()).get(UserModel.class);
    }
}

Summary

Public constructors

Construct a new ViewModel instance.

ViewModel(@NonNull Closeable[] closeables)

Construct a new ViewModel instance.

Public methods

void

Add a new Closeable object that will be closed directly before onCleared is called.

final void

Add a new Closeable object that will be closed directly before onCleared is called.

final @Nullable T
<T extends Closeable> getCloseable(@NonNull String key)

Returns the closeable previously added with addCloseable with the given key.

Protected methods

void

This method will be called when this ViewModel is no longer used and will be destroyed.

Extension functions

final @NonNull CoroutineScope

CoroutineScope tied to this ViewModel.

Public constructors

ViewModel

Added in 2.0.0
public ViewModel()

Construct a new ViewModel instance.

You should never manually construct a ViewModel outside of a ViewModelProvider.Factory.

ViewModel

public ViewModel(@NonNull Closeable[] closeables)

Construct a new ViewModel instance. Any Closeable objects provided here will be closed directly before onCleared is called.

You should never manually construct a ViewModel outside of a ViewModelProvider.Factory.

Public methods

addCloseable

Added in 2.5.0
public void addCloseable(@NonNull Closeable closeable)

Add a new Closeable object that will be closed directly before onCleared is called.

If onCleared() has already been called, the closeable will not be added, and will instead be closed immediately.

Parameters
@NonNull Closeable closeable

The object that should be closed directly before onCleared is called.

addCloseable

Added in 2.8.0-alpha01
public final void addCloseable(@NonNull String key, @NonNull Closeable closeable)

Add a new Closeable object that will be closed directly before onCleared is called.

If onCleared() has already been called, the closeable will not be added, and will instead be closed immediately.

Parameters
@NonNull String key

A key that allows you to retrieve the closeable passed in by using the same key with getCloseable

@NonNull Closeable closeable

The object that should be closed directly before onCleared is called.

getCloseable

Added in 2.8.0-alpha01
public final @Nullable T <T extends Closeable> getCloseable(@NonNull String key)

Returns the closeable previously added with addCloseable with the given key.

Parameters
@NonNull String key

The key that was used to add the Closeable.

Protected methods

onCleared

Added in 2.0.0
protected void onCleared()

This method will be called when this ViewModel is no longer used and will be destroyed.

It is useful when ViewModel observes some data and you need to clear this subscription to prevent a leak of this ViewModel.

Extension functions

ViewModelKt.getViewModelScope

public final @NonNull CoroutineScope ViewModelKt.getViewModelScope(@NonNull ViewModel receiver)

CoroutineScope tied to this ViewModel. This scope will be canceled when ViewModel will be cleared, i.e ViewModel.onCleared is called

This scope is bound to Dispatchers.Main.immediate