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.

Cmn
android
N
ViewModel(vararg closeables: AutoCloseable)

Creates a new ViewModel.

Cmn
ViewModel(viewModelScope: CoroutineScope)

Creates a new ViewModel.

Cmn
android
ViewModel(
    viewModelScope: CoroutineScope,
    vararg closeables: AutoCloseable
)

Creates a new ViewModel.

Cmn

Public functions

open Unit

Adds an AutoCloseable resource to this ViewModel.

Cmn
Unit
addCloseable(key: String, closeable: AutoCloseable)

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

Cmn
T?

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

Cmn
android
N

Protected functions

open Unit

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

Cmn
android
N

Extension properties

CoroutineScope

The CoroutineScope associated with this ViewModel.

Cmn

Public constructors

ViewModel

ViewModel()

Creates a new ViewModel.

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

ViewModel

ViewModel(vararg closeables: AutoCloseable)

Creates a new ViewModel.

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

Parameters
vararg closeables: AutoCloseable

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

ViewModel

ViewModel(viewModelScope: CoroutineScope)

Creates a new ViewModel.

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

Parameters
viewModelScope: CoroutineScope

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

ViewModel

ViewModel(
    viewModelScope: CoroutineScope,
    vararg closeables: AutoCloseable
)

Creates a new ViewModel.

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

Parameters
viewModelScope: CoroutineScope

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

vararg closeables: AutoCloseable

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

Public functions

addCloseable

open fun addCloseable(closeable: AutoCloseable): Unit

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
closeable: AutoCloseable

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

addCloseable

fun addCloseable(key: String, closeable: AutoCloseable): Unit

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
key: String

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

closeable: AutoCloseable

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

getCloseable

fun <T : AutoCloseable> getCloseable(key: String): T?

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

Parameters
key: String

the key associated with a resource via addCloseable.

Protected functions

onCleared

protected open fun onCleared(): Unit

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.

Clearing Sequence:

  1. Close resources added with a key via addCloseable.

  2. Close resources added via constructor.

  3. Close resources added without a key via addCloseable.

  4. Invoke the onCleared callback.

Extension properties

viewModelScope

val ViewModel.viewModelScopeCoroutineScope

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