Skip to content

Instantly share code, notes, and snippets.

@Vivekban
Last active December 27, 2023 23:57
Show Gist options
  • Save Vivekban/42c0c4e2394f50d3e4fc90383c08e4b6 to your computer and use it in GitHub Desktop.
Save Vivekban/42c0c4e2394f50d3e4fc90383c08e4b6 to your computer and use it in GitHub Desktop.
UiString
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.res.stringResource
import com.crinoid.humotron.R
import com.crinoid.humotron.data.common.AppException
import retrofit2.HttpException
import java.io.IOException
import kotlin.String
/**
* A wrapper class around [StringRes] and [String], useful in display of error messages which
* is combination of predefined error in (StringRes) and runtime server error in (String) form.
*
* It exposes a [string] method which returns text to display.
*
* For example
*
* ```
* class CounterModel: ViewModel() {
* val message = MutableStateFlow<UiString?>(null)
*
* init {
* viewModelScope.launch {
* message.value = R.string.something_went_wrong.ui
* delay(100)
* message.value = "Input Error".ui
* }
* }
* }
*
* @Composable
* fun Page(model: CounterModel) {
*
* val message by model.message.collectAsState()
* val hostState = remember { SnackbarHostState() }
*
* val text = message?.text()
*
* LaunchedEffect(key1 = message) {
* text?.let {
* hostState.showSnackbar(
* message = it
* )
* }
* }
* }
* ```
*/
sealed class UiString {
/**
* A data class that represents a resource string.
*
* @property stringId The resource ID of the string to be displayed.
*/
data class Resource(@StringRes val stringId: Int) : UiString()
/**
* A data class that represents a dynamic string ex error from server.
*
* @property string The text to be displayed.
*/
data class String(val string: kotlin.String) : UiString()
}
/**
* A helper composable method provides the text of [UiString].
*
* @return The content of this UI text.
*/
@Composable
@ReadOnlyComposable
fun UiString.string(): String = when (this) {
is UiString.Resource -> stringResource(id = stringId)
is UiString.String -> string
}
/** Helper method convert any string to UIString */
inline val String.uiString: UiString get() = UiString.String(this)
/** Helper method convert any [StringRes] to UIString */
inline val Int.uiString: UiString get() = UiString.Resource(this)
/** Helper method convert any [Throwable] to UIString */
inline val Throwable.uiString: UiString
get() = when (this) {
is NullPointerException -> R.string.null_pointer_msg.uiString
is IOException -> R.string.io_exception_msg.uiString
is HttpException -> R.string.http_exception_msg.uiString
else -> message?.ui ?: R.string.something_went_wrong.ui
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment