LiveData

ObserverLiveData

Parameters:

  • owner: The LifecycleOwner (typically an Activity or Fragment) to which the LiveData is scoped.

  • onLoading: A callback function to be invoked when the state is Loading.

  • onSuccess: A callback function to be invoked when the state is Success, with the successful data passed as a parameter.

  • onEmpty: An optional callback function to be invoked when the state is Empty.

  • onFailure: A callback function to be invoked when the state is Failure, with the failure message passed as a parameter.

Process:

Observes the LiveData and invokes the appropriate callback based on the current state (Default, Loading, Failure, Empty, or Success).

Example:

To use this function, you'll need a LiveData<Resource<T>> and an Activity or Fragment to observe it. Here’s an example:

viewModel.myLiveData.observerLiveData(
    owner = this,
    onLoading = { showLoading() },
    onSuccess = { data -> showData(data) },
    onEmpty = { showEmptyState() },
    onFailure = { message -> showError(message) }
)

This extension function allows you to cleanly handle different states of a LiveData<Resource<T>> in your Activity or Fragment. It improves code readability and maintainability by centralizing the state handling logic.

Last updated