Google は、黒人コミュニティに対する人種平等の促進に取り組んでいます。取り組みを見る

androidx.lifecycle

Interfaces

DefaultLifecycleObserver

Callback interface for listening to LifecycleOwner state changes.

HasDefaultViewModelProviderFactory

Interface that marks a ViewModelStoreOwner as having a default ViewModelProvider.Factory for use with ViewModelProvider#ViewModelProvider(ViewModelStoreOwner).

LifecycleEventObserver

Class that can receive any lifecycle change and dispatch it to the receiver.

LifecycleObserver

Marks a class as a LifecycleObserver.

LifecycleOwner

A class that has an Android lifecycle.

LifecycleRegistryOwner

LiveDataScope

Interface that allows controlling a LiveData from a coroutine block.

Observer

A simple callback that can receive from LiveData.

Factory

Implementations of Factory interface are responsible to instantiate ViewModels.

ViewModelStoreOwner

A scope that owns ViewModelStore.

Classes

AbstractSavedStateViewModelFactory

Skeleton of androidx.

AndroidViewModel

Application context aware ViewModel.

Lifecycle

Defines an object that has an Android Lifecycle.

LifecycleCoroutineScope

CoroutineScope tied to a Lifecycle and Dispatchers.Main.immediate

LifecycleRegistry

An implementation of Lifecycle that can handle multiple observers.

LifecycleService

A Service that is also a LifecycleOwner.

LiveData

LiveData is a data holder class that can be observed within a given lifecycle.

LiveDataReactiveStreams

Adapts LiveData input and output to the ReactiveStreams spec.

MediatorLiveData

LiveData subclass which may observe other LiveData objects and react on OnChanged events from them.

MutableLiveData

LiveData which publicly exposes setValue(T) and postValue(T) method.

ProcessLifecycleOwner

Class that provides lifecycle for the whole application process.

SavedStateHandle

A handle to saved state passed down to androidx.lifecycle.ViewModel.

SavedStateViewModelFactory

androidx.lifecycle.ViewModelProvider.Factory that can create ViewModels accessing and contributing to a saved state via SavedStateHandle received in a constructor.

ServiceLifecycleDispatcher

Helper class to dispatch lifecycle events for a service.

Transformations

Transformation methods for LiveData.

ViewModel

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment.

ViewModelLazy

An implementation of Lazy used by androidx.fragment.app.Fragment.viewModels and androidx.activity.ComponentActivity.viewmodels.

ViewModelProvider

An utility class that provides ViewModels for a scope.

ViewModelProviders

Utilities methods for ViewModelStore class.

ViewModelStore

Class to store ViewModels.

ViewModelStores

Factory methods for ViewModelStore class.

ViewTreeLifecycleOwner

Accessors for finding a view tree-local LifecycleOwner that reports the lifecycle for the given view.

ViewTreeViewModelStoreOwner

Accessors for finding a view tree-local ViewModelStoreOwner that allows access to a ViewModelStore for the given view.

Exceptions

LifecycleDestroyedException

A CancellationException that indicates that the Lifecycle associated with an operation reached the Lifecycle.State.DESTROYED state before the operation could complete.

Annotations

OnLifecycleEvent

Top-level functions summary

LiveData<T>
liveData(context: CoroutineContext = EmptyCoroutineContext, timeoutInMs: Long = DEFAULT_TIMEOUT, block: suspend LiveDataScope<T>.() -> Unit)

Builds a LiveData that has values yielded from the given block that executes on a LiveDataScope.

LiveData<T>
liveData(context: CoroutineContext = EmptyCoroutineContext, timeout: Duration, block: suspend LiveDataScope<T>.() -> Unit)

Builds a LiveData that has values yielded from the given block that executes on a LiveDataScope.

Extension functions summary

For android.view.View
LifecycleOwner?

Locates the LifecycleOwner responsible for managing this View, if present.

ViewModelStoreOwner?

Locates the ViewModelStoreOwner associated with this View, if present.

For kotlinx.coroutines.flow.Flow
LiveData<T>
Flow<T>.asLiveData(context: CoroutineContext = EmptyCoroutineContext, timeoutInMs: Long = DEFAULT_TIMEOUT)

Creates a LiveData that has values collected from the origin Flow.

LiveData<T>
Flow<T>.asLiveData(context: CoroutineContext = EmptyCoroutineContext, timeout: Duration)

Creates a LiveData that has values collected from the origin Flow.

For org.reactivestreams.Publisher
LiveData<T>
Publisher<T>.toLiveData()

Creates an observable LiveData stream from a ReactiveStreams Publisher.

For LiveData
Flow<T>

Creates a Flow containing values dispatched by originating LiveData: at the start a flow collector receives the latest value held by LiveData and then observes LiveData updates.

LiveData<X>

Creates a new LiveData object does not emit a value until the source this LiveData value has been changed.

LiveData<Y>
LiveData<X>.map(crossinline transform: (X) -> Y)

Returns a LiveData mapped from this LiveData by applying transform to each value set on this LiveData.

Observer<T>
LiveData<T>.observe(owner: LifecycleOwner, crossinline onChanged: (T) -> Unit)

Adds the given onChanged lambda as an observer within the lifespan of the given owner and returns a reference to observer.

LiveData<Y>
LiveData<X>.switchMap(crossinline transform: (X) -> LiveData<Y>)

Returns a LiveData mapped from the input this LiveData by applying transform to each value set on this.

Publisher<T>

Adapts the given LiveData stream to a ReactiveStreams Publisher.

For ViewModelProvider
VM

Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or an activity), associated with this ViewModelProvider.

For LifecycleOwner
suspend T
LifecycleOwner.whenCreated(block: suspend CoroutineScope.() -> T)

Runs the given block when the LifecycleOwner's Lifecycle is at least in Lifecycle.State.CREATED state.

suspend T
LifecycleOwner.whenResumed(block: suspend CoroutineScope.() -> T)

Runs the given block when the LifecycleOwner's Lifecycle is at least in Lifecycle.State.RESUMED state.

suspend T
LifecycleOwner.whenStarted(block: suspend CoroutineScope.() -> T)

Runs the given block when the LifecycleOwner's Lifecycle is at least in Lifecycle.State.STARTED state.

suspend R
LifecycleOwner.withCreated(crossinline block: () -> R)

Run block with this LifecycleOwner's Lifecycle in a Lifecycle.State of at least Lifecycle.State.CREATED and resume with the result.

suspend R
LifecycleOwner.withResumed(crossinline block: () -> R)

Run block with this LifecycleOwner's Lifecycle in a Lifecycle.State of at least Lifecycle.State.RESUMED and resume with the result.

suspend R
LifecycleOwner.withStarted(crossinline block: () -> R)

Run block with this LifecycleOwner's Lifecycle in a Lifecycle.State of at least Lifecycle.State.STARTED and resume with the result.

suspend R
LifecycleOwner.withStateAtLeast(state: Lifecycle.State, crossinline block: () -> R)

Run block with this LifecycleOwner's Lifecycle in a Lifecycle.State of at least state and resume with the result.

For Lifecycle
suspend T
Lifecycle.whenCreated(block: suspend CoroutineScope.() -> T)

Runs the given block when the Lifecycle is at least in Lifecycle.State.CREATED state.

suspend T
Lifecycle.whenResumed(block: suspend CoroutineScope.() -> T)

Runs the given block when the Lifecycle is at least in Lifecycle.State.RESUMED state.

suspend T
Lifecycle.whenStarted(block: suspend CoroutineScope.() -> T)

Runs the given block when the Lifecycle is at least in Lifecycle.State.STARTED state.

suspend T
Lifecycle.whenStateAtLeast(minState: Lifecycle.State, block: suspend CoroutineScope.() -> T)

Runs the given block on a CoroutineDispatcher that executes the block on the main thread and suspends the execution unless the Lifecycle's state is at least minState.

suspend R
Lifecycle.withCreated(crossinline block: () -> R)

Run block with this Lifecycle in a Lifecycle.State of at least Lifecycle.State.CREATED and resume with the result.

suspend R
Lifecycle.withResumed(crossinline block: () -> R)

Run block with this Lifecycle in a Lifecycle.State of at least Lifecycle.State.RESUMED and resume with the result.

suspend R
Lifecycle.withStarted(crossinline block: () -> R)

Run block with this Lifecycle in a Lifecycle.State of at least Lifecycle.State.STARTED and resume with the result.

suspend R
Lifecycle.withStateAtLeast(state: Lifecycle.State, crossinline block: () -> R)

Run block with this Lifecycle in a Lifecycle.State of at least state and resume with the result.

Extension properties summary

Top-level functions

liveData

fun <T> liveData(
    context: CoroutineContext = EmptyCoroutineContext,
    timeoutInMs: Long = DEFAULT_TIMEOUT,
    block: suspend LiveDataScope<T>.() -> Unit
): LiveData<T>

Builds a LiveData that has values yielded from the given block that executes on a LiveDataScope.

The block starts executing when the returned LiveData becomes active. If the LiveData becomes inactive while the block is executing, it will be cancelled after timeoutInMs milliseconds unless the LiveData becomes active again before that timeout (to gracefully handle cases like Activity rotation). Any value LiveDataScope.emited from a cancelled block will be ignored.

After a cancellation, if the LiveData becomes active again, the block will be re-executed from the beginning. If you would like to continue the operations based on where it was stopped last, you can use the LiveDataScope.latestValue function to get the last LiveDataScope.emited value.

If the block completes successfully or is cancelled due to reasons other than LiveData becoming inactive, it will not be re-executed even after LiveData goes through active inactive cycle.

As a best practice, it is important for the block to cooperate in cancellation. See kotlin coroutines documentation for details https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html.

The timeoutInMs can be changed to fit different use cases better, for example increasing it will give more time to the block to complete even if LiveData is inactive. It is good for cases when block is finite (meaning it can complete successfully) and is costly to restart. Otherwise if a block is cheap to restart, decreasing the timeoutInMs value will allow to yield less values that aren't consumed by anything.

// a simple LiveData that receives value 3, 3 seconds after being observed for the first time.
val data : LiveData<Int> = liveData {
    delay(3000)
    emit(3)
}


// a LiveData that fetches a `User` object based on a `userId` and refreshes it every 30 seconds
// as long as it is observed
val userId : LiveData<String> = ...
val user = userId.switchMap { id ->
    liveData {
      while(true) {
        // note that `while(true)` is fine because the `delay(30_000)` below will cooperate in
        // cancellation if LiveData is not actively observed anymore
        val data = api.fetch(id) // errors are ignored for brevity
        emit(data)
        delay(30_000)
      }
    }
}

// A retrying data fetcher with doubling back-off
val user = liveData {
    var backOffTime = 1_000
    var succeeded = false
    while(!succeeded) {
        try {
            emit(api.fetch(id))
            succeeded = true
        } catch(ioError : IOException) {
            delay(backOffTime)
            backOffTime *= minOf(backOffTime * 2, 60_000)
        }
    }
}

// a LiveData that tries to load the `User` from local cache first and then tries to fetch
// from the server and also yields the updated value
val user = liveData {
    // dispatch loading first
    emit(LOADING(id))
    // check local storage
    val cached = cache.loadUser(id)
    if (cached != null) {
        emit(cached)
    }
    if (cached == null || cached.isStale()) {
        val fresh = api.fetch(id) // errors are ignored for brevity
        cache.save(fresh)
        emit(fresh)
    }
}

// a LiveData that immediately receives a LiveData<User> from the database and yields it as a
// source but also tries to back-fill the database from the server
val user = liveData {
    val fromDb: LiveData<User> = roomDatabase.loadUser(id)
    emitSource(fromDb)
    val updated = api.fetch(id) // errors are ignored for brevity
    // Since we are using Room here, updating the database will update the `fromDb` LiveData
    // that was obtained above. See Room's documentation for more details.
    // https://developer.android.com/training/data-storage/room/accessing-data#query-observable
    roomDatabase.insert(updated)
}
Parameters
context: CoroutineContext = EmptyCoroutineContext The CoroutineContext to run the given block in. Defaults to EmptyCoroutineContext combined with Dispatchers.Main.immediate
timeoutInMs: Long = DEFAULT_TIMEOUT The timeout in ms before cancelling the block if there are no active observers (LiveData.hasActiveObservers. Defaults to DEFAULT_TIMEOUT.
block: suspend LiveDataScope<T>.() -> Unit The block to run when the LiveData has active observers.

liveData

@RequiresApi(26) fun <T> liveData(
    context: CoroutineContext = EmptyCoroutineContext,
    timeout: Duration,
    block: suspend LiveDataScope<T>.() -> Unit
): LiveData<T>

Builds a LiveData that has values yielded from the given block that executes on a LiveDataScope.

The block starts executing when the returned LiveData becomes active. If the LiveData becomes inactive while the block is executing, it will be cancelled after the timeout duration unless the LiveData becomes active again before that timeout (to gracefully handle cases like Activity rotation). Any value LiveDataScope.emited from a cancelled block will be ignored.

After a cancellation, if the LiveData becomes active again, the block will be re-executed from the beginning. If you would like to continue the operations based on where it was stopped last, you can use the LiveDataScope.latestValue function to get the last LiveDataScope.emited value.

If the block completes successfully or is cancelled due to reasons other than LiveData becoming inactive, it will not be re-executed even after LiveData goes through active inactive cycle.

As a best practice, it is important for the block to cooperate in cancellation. See kotlin coroutines documentation for details https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html.

The timeout can be changed to fit different use cases better, for example increasing it will give more time to the block to complete even if LiveData is inactive. It is good for cases when block is finite (meaning it can complete successfully) and is costly to restart. Otherwise if a block is cheap to restart, decreasing the timeout value will allow to yield less values that aren't consumed by anything.

// a simple LiveData that receives value 3, 3 seconds after being observed for the first time.
val data : LiveData<Int> = liveData {
    delay(3000)
    emit(3)
}


// a LiveData that fetches a `User` object based on a `userId` and refreshes it every 30 seconds
// as long as it is observed
val userId : LiveData<String> = ...
val user = userId.switchMap { id ->
    liveData {
      while(true) {
        // note that `while(true)` is fine because the `delay(30_000)` below will cooperate in
        // cancellation if LiveData is not actively observed anymore
        val data = api.fetch(id) // errors are ignored for brevity
        emit(data)
        delay(30_000)
      }
    }
}

// A retrying data fetcher with doubling back-off
val user = liveData {
    var backOffTime = 1_000
    var succeeded = false
    while(!succeeded) {
        try {
            emit(api.fetch(id))
            succeeded = true
        } catch(ioError : IOException) {
            delay(backOffTime)
            backOffTime *= minOf(backOffTime * 2, 60_000)
        }
    }
}

// a LiveData that tries to load the `User` from local cache first and then tries to fetch
// from the server and also yields the updated value
val user = liveData {
    // dispatch loading first
    emit(LOADING(id))
    // check local storage
    val cached = cache.loadUser(id)
    if (cached != null) {
        emit(cached)
    }
    if (cached == null || cached.isStale()) {
        val fresh = api.fetch(id) // errors are ignored for brevity
        cache.save(fresh)
        emit(fresh)
    }
}

// a LiveData that immediately receives a LiveData<User> from the database and yields it as a
// source but also tries to back-fill the database from the server
val user = liveData {
    val fromDb: LiveData<User> = roomDatabase.loadUser(id)
    emitSource(fromDb)
    val updated = api.fetch(id) // errors are ignored for brevity
    // Since we are using Room here, updating the database will update the `fromDb` LiveData
    // that was obtained above. See Room's documentation for more details.
    // https://developer.android.com/training/data-storage/room/accessing-data#query-observable
    roomDatabase.insert(updated)
}
Parameters
timeout: