Last active
October 9, 2024 12:56
-
-
Save stevdza-san/cca20eff9f2c4c7d783ffd0a0061b352 to your computer and use it in GitHub Desktop.
Useful wrapper class for handling the data in Jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} | |
} | |
} | |
} |
You're welcome. Thank you for making tutorials!
This gonna be very useful for me Thanks Stevza-san
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@AKnght Thanks for the feedback. I've updated the code.