Anton V
09/20/2024, 7:09 PMResourceEnvironment
(with manually updated language) for invoking getString(env: ResourceEnvironment, res: StringResource)
?)
I'm developing a KMP library that is shared between Android/iOS/JS, and expose localized texts. The JS (browser) target must have an ability to manually change the language of these strings.
This library uses compose.components.resources
and it works well with default localization behavior, for instance - reading navigator.language
for JS browser target.
The issue arise if you need to change the default behavior and provide a language by yourself (e.g. when a user selects another language from web-app/chrome-extension settings - and you need to apply this language only for you webApp/chromeExtension).
There is a public method suspend fun getString(environment: ResourceEnvironment, resource: StringResource): String
(src). But it use ResourceEnvironment
(src) that has internal constructor
, immutable, and has no public factory (like .copy()
, .clone()
or .newInstance()
), so it can't be instantiated manually. And we're not in JVM world to use reflection and .setAccessible(true)
.
The question:
• is there a way to instantiate a custom ResourceEnvironment
?
• if "no" - will it be possible to allow custom instantiation? for instance via a factory method, with at least customizable "language" field, e.g.:
class ResourceEnvironment internal constructor(...) {
...
fun withLanguage(language: String): ResourceEnvironment =
ResourceEnvironment(
language = LanguageQualifier(language),
region = this.region,
theme = this.theme,
density = this.density,
)
}