Skip to main content

Observing LiveData Updates

API Quick Reference

Signature: fun <T> ComponentScope.useLiveData(liveData: LiveData<T>): T?

RequirementDescription
LifecycleOwnerMust set via withLifecycleOwnerTreeProp or setLifecycleOwnerTreeProp
Lifecycle AwarenessOnly observes when lifecycle is at least STARTED
Auto-cleanupStops observing when lifecycle reaches DESTROYED

Import:

import com.facebook.litho.useLiveData

Dependency: com.facebook.litho:litho-live-data-kotlin

The useLiveData hook provides support to observe LiveData updates inside a Component.

class UseLiveDataComponent(private val viewModel: FakeLiveDataViewModel = FakeLiveDataViewModel()) :
KComponent() {

override fun ComponentScope.render(): Component? {
val viewState = useLiveData(viewModel.liveData) ?: error("should not be null")

return Column {
child(HeaderComponent(viewState.name))
child(
CounterComponent(
counter = viewState.counter,
onCounterClick = { viewModel.onIncrementCounterClick() },
),
)
}
}
}

This hook will start observing the given LiveData and return its latest value every time it changes. The values observed are internally represented as Litho's State, hence it will trigger a new layout calculation for any LiveData value change.

Integrating Litho with the LifecycleOwner​

A core principle for LiveData observation is the LifecycleOwner, which defines at what points the Observer can listen to value changes. In order to use useLiveData, you must set the lifecycle owner using withLifecycleOwnerTreeProp when building the ComponentTree and pass the appropriate LifecycleOwner to it, or calling setLifecycleOwnerTreeProp on LithoView. This can be done as shown in the sample below:

class LithoViewWithLifecycleOwnerFragment : Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
val componentContext = ComponentContext(requireContext())

// Create a ComponentTree with the lifecycle owner tree prop set
val componentTree =
ComponentTree.create(componentContext, LifecycleOwnerTreePropSampleComponent())
.withLifecycleOwnerTreeProp(this)
.enableChildClipping(true)
.build()

// Create a LithoView with the ComponentTree
val lithoView = LithoView(componentContext)
lithoView.componentTree = componentTree

return lithoView
}
}

The LiveData observation will respect the LifecycleOwner lifecycle. Therefore, it will not consume updates if the Lifecycle.State is not at least Lifecycle.State.STARTED, and it will automatically stop being observed if the given LifecycleOwner moves to Lifecycle.State.DESTROYED.

Dependencies​

In Gradle, you should add the following dependency to the build.gradle file:

dependencies {
implementation 'com.facebook.litho:litho-live-data-kotlin:0.50.2'
}

See Also​