State Flow (Jetpack Compose)
Collect State Flow (Jetpack Compose)
The collectStateFlow
extension function is designed to simplify handling the state updates emitted by a StateFlow<Resource<T>>
in Jetpack Compose composables. It takes a Resource<T>
type, which represents the different states a data fetching operation can be in:
Resource.Default
: Initial state before data fetching begins.Resource.Loading
: Data is being fetched.Resource.Empty
: Data fetching completed but no data was found.Resource.Failure
: Data fetching failed with an optional error message.Resource.Success
: Data fetching was successful, containing the fetched data.
Function Parameters:
onLoading
: A composable function to be invoked when the state isResource.Loading
. This allows you to display a loading indicator while data is being fetched.onEmpty
(optional): A composable function to be invoked when the state isResource.Empty
. This is useful for handling cases where no data is available.onFailure
: A composable function that takes an optional error message string as a parameter. It's invoked when the state isResource.Failure
. You can use this to display an error message to the user.onSuccess
: A composable function that takes the fetched data (T
) as a parameter. It's invoked when the state isResource.Success
. This is where you typically render the retrieved data in your composable.
How it Works:
The function calls
collectAsState()
on theStateFlow
to convert it into aState<Resource<T>>
. This allows you to access the current state value within the composable.It retrieves the current state value using
value
.It uses a
when
expression to handle different state types:If the state is
Resource.Default
, nothing happens (this state is usually not of interest).If the state is
Resource.Loading
, theonLoading
composable is invoked to display a loading indicator.If the state is
Resource.Empty
, the optionalonEmpty
composable is invoked (if provided) to handle the case where no data is found.If the state is
Resource.Failure
, theonFailure
composable is invoked with the error message (if available) to display an error message.If the state is
Resource.Success
, theonSuccess
composable is invoked with the fetched data to render it in your composable.
Usage:
A loading indicator ("Loading...") is displayed when the state is
Resource.Loading
.An optional message ("No data available") is shown when the state is
Resource.Empty
.If data fetching fails and an error message is available, it's displayed ("Error: $errorMessage").
When data is successfully fetched, it's rendered in the text ("Fetched data: $data").
This extension function helps you write cleaner and more concise composables by handling the different states of a StateFlow<Resource<T>>
in a more structured way.
Last updated