ActivityViewModelLazyKt

Added in 1.9.0

public final class ActivityViewModelLazyKt


Summary

Public methods

static final @NonNull Lazy<@NonNull VM>
@MainThread
<VM extends ViewModel> viewModels(
    @NonNull ComponentActivity receiver,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

Returns a Lazy delegate to access the ComponentActivity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.

static final @NonNull Lazy<@NonNull T>
@MainThread
<T extends ViewModel> viewModels(
    @NonNull ComponentActivity receiver,
    @NonNull String key,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

Returns a Lazy delegate for this ComponentActivity's ViewModel identified by key.

Public methods

@MainThread
public static final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> viewModels(
    @NonNull ComponentActivity receiver,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

Returns a Lazy delegate to access the ComponentActivity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.

class MyComponentActivity : ComponentActivity() {
val viewmodel: MyViewModel by viewModels()
}

This property can be accessed only after the Activity is attached to the Application, and access prior to that will result in IllegalArgumentException.

@MainThread
public static final @NonNull Lazy<@NonNull T> <T extends ViewModel> viewModels(
    @NonNull ComponentActivity receiver,
    @NonNull String key,
    Function0<@NonNull CreationExtras> extrasProducer,
    Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)

Returns a Lazy delegate for this ComponentActivity's ViewModel identified by key.

Delegates with the same key and ViewModel type share the same instance. Different keys allow multiple instances of the same ViewModel type in this activity.

class MyComponentActivity : ComponentActivity() {
val primaryViewModel: MyViewModel by viewModels(key = "primary")
val secondaryViewModel: MyViewModel by viewModels(key = "secondary")
}

This property can be accessed only after the Activity is attached to the Application. Access before that results in an IllegalArgumentException.

Parameters
@NonNull String key

identifier used to store and retrieve the ViewModel

Function0<@NonNull CreationExtras> extrasProducer

producer of the CreationExtras used to create the ViewModel

Function0<@NonNull ViewModelProvider.Factory> factoryProducer

producer of the Factory used to create the ViewModel