Monday, 5 July 2021

How to use preference datastore in Application Class in JetPack Compose Android to Change theme?

I have set up the theme for my android application using jetpack compose. I have declared my variable in the Application class (TranslateApplication) as

val isDark = mutableStateOf(false)

I am using this value in my MainActivity.kt Such as

  setContent {

        JetnewsTheme(darkTheme = translateApplication.isDark.value) { ......

Now I want to get the isDark using preference datastore and I have defined the following code.

@HiltAndroidApp
class TranslateApplication: Application(){
    val android.content.Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = Constants.SETTINGS)

    val isDark = mutableStateOf(false)


    override fun onCreate() {
        super.onCreate()
        GlobalScope.launch {
            read()
        }
    }

    suspend fun read() {
        val dataStoreKey = booleanPreferencesKey(Constants.THEME)
        val preferences = dataStore.data.first()

        isDark.value =  preferences[dataStoreKey]  ?: false
    }
}

first, I am assigning the value to isDark and then using GlobalScope in onCreate to get preference datastore and it doesn't seem to be the best practice to change the theme like this in a jetpack compose.

My question is that what show be the preferred way to get the Stored Value and change the theme using Application Class in the jetPack Compose.



from How to use preference datastore in Application Class in JetPack Compose Android to Change theme?

No comments:

Post a Comment