Skip to content

Instantly share code, notes, and snippets.

@stevdza-san
Last active April 12, 2024 11:10
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save stevdza-san/cca20eff9f2c4c7d783ffd0a0061b352 to your computer and use it in GitHub Desktop.
Save stevdza-san/cca20eff9f2c4c7d783ffd0a0061b352 to your computer and use it in GitHub Desktop.
Useful wrapper class for handling the data in Jetpack Compose
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.runtime.Composable
sealed class RequestState<out T> {
data object Idle : RequestState<Nothing>()
data object Loading : RequestState<Nothing>()
data class Success<T>(val data: T) : RequestState<T>()
data class Error(val message: String) : RequestState<Nothing>()
fun isLoading() = this is Loading
fun isSuccess() = this is Success
fun isError() = this is Error
/**
* Returns data from a [Success].
* @throws ClassCastException If the current state is not [Success]
* */
fun getSuccessData() = (this as Success).data
fun getSuccessDataOrNull(): T? {
return try {
(this as Success).data
} catch (e: Exception) {
null
}
}
/**
* Returns an error message from an [Error]
* @throws ClassCastException If the current state is not [Error]
* */
fun getErrorMessage() = (this as Error).message
fun getErrorMessageOrNull(): String? {
return try {
(this as Error).message
} catch (e: Exception) {
null
}
}
@Composable
fun DisplayResult(
onIdle: (@Composable () -> Unit)? = null,
onLoading: @Composable () -> Unit,
onSuccess: @Composable (T) -> Unit,
onError: @Composable (String) -> Unit,
) {
AnimatedContent(
targetState = this,
transitionSpec = {
fadeIn(tween(durationMillis = 300)) togetherWith
fadeOut(tween(durationMillis = 300))
},
label = "Content Animation"
) { state ->
when (state) {
is Idle -> {
onIdle?.invoke()
}
is Loading -> {
onLoading()
}
is Success -> {
onSuccess(state.getSuccessData())
}
is Error -> {
onError(state.getErrorMessage())
}
}
}
}
}
@AKnght
Copy link

AKnght commented Mar 23, 2024

Typo:
onSuccess(state.getSuccessDate())

Change to:
onSuccess(state.getSuccessData())

@stevdza-san
Copy link
Author

@AKnght Thanks for the feedback. I've updated the code.

@AKnght
Copy link

AKnght commented Mar 23, 2024

You're welcome. Thank you for making tutorials!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment