ViewModelKt

public final class ViewModelKt


Summary

Public methods

static final @Composable @NonNull VM
<VM extends ViewModel> viewModel(
    @NonNull ViewModelStoreOwner viewModelStoreOwner,
    @Nullable String key,
    @Nullable ViewModelProvider.Factory factory
)

Returns an existing ViewModel or creates a new one in the given owner (usually, a fragment or an activity), defaulting to the owner provided by LocalViewModelStoreOwner.

static final @Composable @NonNull VM
<VM extends ViewModel> viewModel(
    @NonNull Class<@NonNull VM> modelClass,
    @NonNull ViewModelStoreOwner viewModelStoreOwner,
    @Nullable String key,
    @Nullable ViewModelProvider.Factory factory
)

Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or an activity)

Public methods

viewModel

@Composable
@NonNull
public static final @Composable VM <VM extends ViewModel> viewModel(
    @NonNull ViewModelStoreOwner viewModelStoreOwner,
    @Nullable String key,
    @Nullable ViewModelProvider.Factory factory
)

Returns an existing ViewModel or creates a new one in the given owner (usually, a fragment or an activity), defaulting to the owner provided by LocalViewModelStoreOwner.

The created ViewModel is associated with the given viewModelStoreOwner and will be retained as long as the owner is alive (e.g. if it is an activity, until it is finished or process is killed).

Parameters
@NonNull ViewModelStoreOwner viewModelStoreOwner

The owner of the ViewModel that controls the scope and lifetime of the returned ViewModel. Defaults to using LocalViewModelStoreOwner.

@Nullable String key

The key to use to identify the ViewModel.

@Nullable ViewModelProvider.Factory factory

The ViewModelProvider.Factory that should be used to create the ViewModel or null if you would like to use the default factory from the LocalViewModelStoreOwner

Returns
@Composable VM

A ViewModel that is an instance of the given VM type.

viewModel

@Composable
@NonNull
public static final @Composable VM <VM extends ViewModel> viewModel(
    @NonNull Class<@NonNull VM> modelClass,
    @NonNull ViewModelStoreOwner viewModelStoreOwner,
    @Nullable String key,
    @Nullable ViewModelProvider.Factory factory
)

Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or an activity)

The created ViewModel is associated with the given viewModelStoreOwner and will be retained as long as the scope is alive (e.g. if it is an activity, until it is finished or process is killed).

Parameters
@NonNull Class<@NonNull VM> modelClass

The class of the ViewModel to create an instance of it if it is not present.

@NonNull ViewModelStoreOwner viewModelStoreOwner

The scope that the created ViewModel should be associated with.

@Nullable String key

The key to use to identify the ViewModel.

Returns
@Composable VM

A ViewModel that is an instance of the given VM type.