Last active
April 8, 2023 10:26
-
-
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
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 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