How can you get a string from resources strings in...
# compose-desktop
p
How can you get a string from resources strings in a viewmodel? We don't have LocalContext or similar thing here, and I need to recover it, because I need to store in the appstate a string resource value with some parameters
c
Just keep the id as long as you are able to resolve to the actual string. No need to resolve in the view model. If you have additional format arguments create a wrapper an safe along. i.e.
Copy code
data class StringResource(
    val id: Int,
    val args: Array<Any>?
)
and use it like this
Copy code
@Composable
    fun MyComposable() {
        val stringResource =
            StringResource(
                id = R.string.ok,
                args = arrayOf("Foo", 1),
            )

        Text(
            stringResource(stringResource.id, *stringResource.args.orEmpty()),
        )
    }
p
wow, I did a few mins ago exactly what you propossed me
Copy code
data class LinesDBScreenUiState(
    val loading: Boolean = false,
    val message: StringResourceWithParameters? = null,
    val data: List<Line> = emptyList()
)

data class StringResourceWithParameters(
    val resource: StringResource,
    val parameters: Any = emptyList<Any>()
)
c
List
will not work though if you need to send id as
varags
to the
stringResource
check the syntax in my code snippet espacially the
***stringResource.args
p
it's working, I'm using like this:
Copy code
stringResource(message.resource, message.parameters),
c
this will pass only one argument and that as a list but if you have multiple args that will not work.
so what your code is doing is calling
stringResource(id, listOf("2", "3"))
instead of
stringResource(id, "2", "3")
You can pass a variable number of arguments (`vararg`) with names using the
spread
operator:
```fun foo(vararg strings: String) { /*...*/ }
foo(strings = *arrayOf("a", "b", "c"))```
h
BTW you don’t need the spread operator if you pass an array and mention the parameter name explicitly. IntelliJ warns you about this too.
c
So you are saying the documentation is wrong? Looks like the docs are outdated. Curious which compiler version is needed for that? Maybe a k2 feature?
p
is not possible to do it in some way that I don't need to call arrayOf if there is only one arg?
c
if you are sure there is only one then its fine without the array. I’d just be careful with that assumption 😉
p
hehe
well, it worked! thank you. On the other hand I see this as a little complex, probably if I read these lines in one year it will be hard to understand
but as no simpler way to do this available, it will be the final implementation
s
You can try
suspend fun getString(res: StringRes)
if you are using Compose Components Resources as Resources library.
p
how can that be used in compose for desktop?
p
is a good practice to recover resource value in a viewmodel then?
s
It is very simple.
186 Views