Skip to content

Instantly share code, notes, and snippets.

@byaruhaf
Forked from stevdza-san/RequestState.kt
Created March 17, 2024 05:32
Show Gist options
  • Save byaruhaf/7af0e72752b9ca00ff47a89c597e67b3 to your computer and use it in GitHub Desktop.
Save byaruhaf/7af0e72752b9ca00ff47a89c597e67b3 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 () -> Unit,
onError: @Composable () -> 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()
}
is Error -> {
onError()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment