Hey friends, is it possible to change the locale o...
# compose
s
Hey friends, is it possible to change the locale of a Compose Multiplatform app in real-time across all platforms? For example, updating the app’s language instantly when the user selects their preferred language. If yes, could someone guide me on how to achieve this?
How do I set up my Compose Multiplatform app so that the locale updates in real-time when the user selects a language? For example. I've this
viewmodel
which should be able to change the locale in real-time based on the events it received from the composable.
Copy code
// Viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import compose.app.shared.util.LocaleManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import legalbot.user.onboarding.domain.model.language.Language
import legalbot.user.onboarding.domain.useCase.language.LanguageUseCase

internal class LanguagePageViewModel(
    private val languageUseCase: LanguageUseCase,
    private val localeManager: LocaleManager
) : ViewModel() {
    var uiState = MutableStateFlow(value = LanguagePageUiState())
        private set

    init {
        viewModelScope.launch {
            languageUseCase.getLanguages().collect { languages ->
                uiState.update { value ->
                    value.copy(languages = languages)
                }
            }
        }
    }

    fun updateSelectedLanguage(language: Language) {
        languageUseCase.updateSelectedLanguage(language = language)
        localeManager.setLocale(locale = language.locale)
    }
}
Copy code
// Locale manager class
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
expect class LocaleManager {
    fun setLocale(locale: String)
}
p
I believe the question is about remote handling of localization, for example if user changes locale on Android, he wants that same user to have changed localization on iOS too.
s
No, it’s not about remote localization. It’s about making the UI automatically translate as the user selects their language, without needing to restart the app.