androidkotlinandroid-jetpack-datastore

Pattern to access kotlin DataStore values without using suspend functions


I am using a class to store and load data from a DataStore in my kotlin multiplatform app. The class is simple:

class AuthPersistence(
    private val context: Context
) {
    private val Context.dataStore by preferencesDataStore(context.packageName)

    actual suspend fun saveUsername(username: String) {
        context.dataStore.edit {
            it[usernameKey] = username
        }
    }

    actual suspend fun getUsername(): String? {
        return context.dataStore.data.firstOrNull()?.get(usernameKey)
    }

    private val usernameKey = stringPreferencesKey("user_name")
}

The class AuthPersistence is a singleton that I inject using koin. My problem is, that I don't know the best/cleanest way to make the username accessible without calling the suspend function. (Accessing the username directly from a class without launching a coroutine is less complex and the username should rarely change)

My approach would possible be to create an immutable variable that get's changed everytime I save a new username. But as mentioned; I'm not sure if this is the kotlin way.


Solution

  • Thank you for your answers. I found the easiest solution is to wrap the access to a DataStore property in a runBlocking {} block since it is at the end of the day a simple access to a json/protobuf file.