Hi all :android-wave: , `stringResource()` throws ...
# compose-android
a
Hi all 👋 ,
stringResource()
throws
Resources.NotFoundException
exception when the id passed is not valid. Not to catch this? Adding try catch gives this error,
Copy code
Try catch is not supported around composable function invocations.
s
I'd you look at what it does internally, does it look like you could do this try catch outside of a composable context? Perhaps grab the resources in composition, and then use a try catch inside a remember which does the fetching? I've never tried smth like this, or try catching inside a remember lambda, but perhaps worth a shot
a
stringResource()
can not be moved inside a
remember
as it needs Composable scope. I am not sure if I understood what you meant. Can you please help share an example?
s
I meant look at what stringResource does internally
resources.getString shouldn't be a composable function
a
Okay. So the suggestion is to use,
Copy code
val resources = LocalContext.current.resources
val string = remember {
    try {
        resources.getString(R.string.string_id)
    } catch (exception: Resources.NotFoundException) {
        null
    }
}
instead of
Copy code
val string = stringResource(
    id = R.string.string_id,
)
I wonder why this is not the default internal implementation for
stringResource()
🤔 .
s
Yeah that was my idea, does this work? Also I don't even know when you have scenarios where the ID isn't found, which scenarios are those?
a
Will try this and share an update later. The scenario is where I need to show some strings based on conditions, I share a UI state data class instance from the ViewModel. As the data will not be available till all the conditions are executed, the initial state will have a default value as
-1
. I have changed that logic to make default as
null
and I do null checks before using
stringResource()
now and it works as expected. But, I was curious to understand the recommendation on exception handling in Compose.
s
It wasn't some recommendation btf, I just suggested doing that since you can't do a try catch in compose code. And I was also curious myself to see if it'd work 😅
👍 1