Skip to main content

useLiveData

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

internal 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 create your LithoView with the AOSPLithoLifecycleProvider and pass the appropriate LifecycleOwner to it. This can be done as shown in the sample below:

class LithoViewCreationFragment : Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LithoView.create(
requireContext(), SampleComponent(), AOSPLithoVisibilityEventsController(this))
}
}

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'
}