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 androidx.activity.ComponentActivity or a androidx.fragment.app.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 androidx.lifecycle.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:

class UserActivity : ComponentActivity {
private val viewModel by viewModels<UserViewModel>()

override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.user_activity_layout)
viewModel.user.observe(this) { user: User ->
// update ui.
}
requireViewById(R.id.button).setOnClickListener {
viewModel.doAction()
}
}
}

ViewModel would be:

class UserViewModel : ViewModel {
private val userLiveData = MutableLiveData<User>()
val user: LiveData<User> get() = userLiveData

init {
// trigger user load.
}

fun 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.

class MyFragment : Fragment {
val viewModel by activityViewModels<UserViewModel>()
}

Summary

Public constructors

Creates a new ViewModel.

Creates a new ViewModel.

ViewModel(@NonNull CoroutineScope viewModelScope)

Creates a new ViewModel.

ViewModel(
    @NonNull CoroutineScope viewModelScope,
    @NonNull AutoCloseable closeables
)

Creates a new ViewModel.

Public methods

void

Adds an AutoCloseable resource to this ViewModel.

final void

Adds an AutoCloseable resource with an associated key to this ViewModel.

final T

Returns the AutoCloseable resource associated to the given key, or null if such a key is not present in this ViewModel.

Protected methods

void

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

Extension functions

final @NonNull CoroutineScope

The CoroutineScope associated with this ViewModel.

Public constructors

ViewModel

Added in 2.0.0
public ViewModel()

Creates a new ViewModel.

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

ViewModel

public ViewModel(@NonNull AutoCloseable closeables)

Creates a new ViewModel.

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

Parameters
@NonNull AutoCloseable closeables

the resources to be closed when the ViewModel is cleared, right before the onCleared method is called.

ViewModel

Added in 2.8.0
public ViewModel(@NonNull CoroutineScope viewModelScope)

Creates a new ViewModel.

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

Parameters
@NonNull CoroutineScope viewModelScope

a CoroutineScope to be cancelled when the ViewModel is cleared, right before the onCleared method is called.

ViewModel

public ViewModel(
    @NonNull CoroutineScope viewModelScope,
    @NonNull AutoCloseable closeables
)

Creates a new ViewModel.

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

Parameters
@NonNull CoroutineScope viewModelScope

a CoroutineScope to be cancelled when the ViewModel is cleared, right before the onCleared method is called.

@NonNull AutoCloseable closeables

the resources to be closed when the ViewModel is cleared, right before the onCleared method is called.

Public methods

addCloseable

public void addCloseable(@NonNull AutoCloseable closeable)

Adds an AutoCloseable resource to this ViewModel. The resource will be closed right before the onCleared method is called.

If onCleared has already been called, the provided resource will not be added and will be closed immediately.

Parameters
@NonNull AutoCloseable closeable

the resource to be closed when the ViewModel is cleared, right before the onCleared method is called.

addCloseable

public final void addCloseable(@NonNull String key, @NonNull AutoCloseable closeable)

Adds an AutoCloseable resource with an associated key to this ViewModel. The resource will be closed right before the onCleared method is called.

If the key already has a resource associated with it, the old resource will be replaced and closed immediately.

If onCleared has already been called, the provided resource will not be added and will be closed immediately.

Parameters
@NonNull String key

the key to associate with the resource, for retrieval with getCloseable.

@NonNull AutoCloseable closeable

the resource to be closed when the ViewModel is cleared, right before the onCleared method is called.

getCloseable

public final T <T extends AutoCloseable> getCloseable(@NonNull String key)

Returns the AutoCloseable resource associated to the given key, or null if such a key is not present in this ViewModel.

Parameters
@NonNull String key

the key associated with a resource via addCloseable.

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 the ViewModel observes data and you need to clear the subscriptions to prevent a memory leak, as the subscriptions might hold a reference to the ViewModel even after it is no longer needed.

For specifics about the clearing sequence, refer to the clear method.

Extension functions

ViewModelKt.getViewModelScope

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

The CoroutineScope associated with this ViewModel.

The CoroutineScope.coroutineContext is configured with:

This scope is automatically cancelled when the ViewModel is cleared, and can be replaced by using the ViewModel constructor overload that takes in a viewModelScope: CoroutineScope.

For background execution, use kotlinx.coroutines.withContext to switch to appropriate dispatchers (e.g., kotlinx.coroutines.IO).

See also
onCleared