Skip to content

Instantly share code, notes, and snippets.

@AsadLeo1995
Last active April 8, 2023 10:26
Show Gist options
  • Save AsadLeo1995/d03242259c60d3ca02c9889ea05c9fe4 to your computer and use it in GitHub Desktop.
Save AsadLeo1995/d03242259c60d3ca02c9889ea05c9fe4 to your computer and use it in GitHub Desktop.
Error handling in kotlin when you have both string & string resource error. Credit @philipplackner
import android.content.Context
import androidx.annotation.StringRes
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
sealed class UiText{
data class DynamicString(val value: String): UiText()
data class StringResource(@StringRes val id: Int,val args: List<Any>): UiText()
fun asString(context: Context): String{
return when(this){
is DynamicString -> value
is StringResource -> context.getString(id,*args.toTypedArray())
}
}
@Composable
fun asString(): String{
return when(this){
is DynamicString -> value
is StringResource -> stringResource(id,*args.toTypedArray())
}
}
}
@Composable
fun ErrorMessage(error: UiText) {
Text(text = error.asString(), color = Color.Red)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment