Implementation of getString() of PreferenceDataStore method

118 Views Asked by At

I am using a custom DataStore which inherits PreferenceDataStore to store preferences for settings activity in my android application. I want to implement the getString() method as the PreferenceDataStore.getString() method doesn't do anything.

-> PreferenceDataStore.getString()

    /**
     * Retrieve a String value from the data store.
     *
     * @param key The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @see #putString(String, String)
     */
    @Nullable
    default String getString(String key, @Nullable String defValue) {
        return defValue;
    }

This is my SettingsPreferences class:

class SettingsPreferences(lifecycleCoroutineScope: LifecycleCoroutineScope, context: Context) :
    PreferenceDataStore() {
    companion object {
        private const val TAG = "SettingsPreferences"
        val THEME = stringPreferencesKey("theme")
    }

    private val scope = lifecycleCoroutineScope
    private val currentContext = context

    override fun putString(key: String?, value: String?) {
        scope.launch {
            currentContext.dataStore.edit {
                it[stringPreferencesKey(key.toString())] = value ?: ""
            }
        }
    }

    override fun getString(key: String?, defValue: String?): String? {
        //TODO implement getString
        return super.getString(key, defValue)
    }

    fun storeTheme(theme: String) {
        putString(THEME.name, theme)
    }

}

I'm not sure whether using kotlin is the problem. I tried this method:

currentContext.dataStore.data.first()[stringPreferencesKey(key.toString())]

but the first() is an async method, so I have to suspend getString() or use coroutine, but getString() method which is an inherited method cannot be suspended and using coroutine, I can't return the value. What or how should I implement for this method?

Note: There is an alternative method to update values in Preference screen in android with custom implementation, but it is hectic and my objective is to implement putString() method so that the PreferenceFragmentCompat class handles it appropriately.

1

There are 1 best solutions below

1
Vahé Khachaturian On

A possible option is to use runblocking, but that's more of a workaround than a solution, so you can use it and come back to your task later on