Yet More Terminology
First, let’s review some new and exciting terms that we need to understand in order to use LiveData
.
LiveData
LiveData
itself is a source of data, both for a point in time and (via an observer) for changes to that data over time. Something will create and hand you a LiveData
object, where the work to get that data and update it over time is handled by some background thread coming from the LiveData
supplier.
Observer
In principle, you can call getValue()
on a LiveData
to get the current value for whatever stream of data the LiveData
is tracking. In practice, this will not be especially common.
Instead, you will register an Observer
with the LiveData
, usually via an observe()
method. Your Observer
will be called with onChanged()
when:
- You start observing and there is already data in the
LiveData
, and - When the
LiveData
finds out about a change in the data
Your onChanged()
method is given the data (a Location
, a SensorEvent
, a Room entity, whatever) on the main application thread, with an eye towards you using it to update the UI by one means or another.
Active State
If a LiveData
was instantiated in a forest, and nobody was there to observe data changes, does the LiveData
really exist?
The answer is: yes, but it hopefully is not consuming any resources.
A LiveData
implementation will be called with onActive()
when it receives its first active observer. Here, “active” means that, if the observer is tied to a LifecycleOwner
, the lifecycle is in the started or resumed state. Conversely, the LiveData
will be called with onInactive()
once it no longer has any active observers, either because all observers have been unregistered or none of them are active, as their lifecycles are all stopped or destroyed.
The idea is that a LiveData
would only start consuming significant system resources — such as requesting GPS fixes — when there are active observers, releasing those resources when there are no more active observers. This works in many cases, though there are some that will require more finesse. For example, given that the GPS radio takes some time before it starts generating GPS fixes, a LiveData
for GPS might want to wait some amount of time after losing its last active observer before releasing the GPS radio, in case a new observer pops up quickly, to avoid delays in getting those GPS fixes.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.