LiveData
ObserverLiveData
Parameters:
owner
: TheLifecycleOwner
(typically anActivity
orFragment
) to which theLiveData
is scoped.onLoading
: A callback function to be invoked when the state isLoading
.onSuccess
: A callback function to be invoked when the state isSuccess
, with the successful data passed as a parameter.onEmpty
: An optional callback function to be invoked when the state isEmpty
.onFailure
: A callback function to be invoked when the state isFailure
, 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:
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