android datastore 同步地读取数据

1,078 阅读1分钟

用runBlocking+Flow.first():

@Suppress("UNCHECKED_CAST")
private fun getDataStorePreferences(name: String, default: T): T {
   return runBlocking {
        App.instance.dataStore.data
                .catch { exception ->
                    // dataStore.data throws an IOException when an error is encountered when reading data
                    if (exception is IOException) {
                        Log.e(TAG, "Error reading preferences.", exception)
                        emit(emptyPreferences())
                    } else {
                        throw exception
                    }
                }.map {
                    it[when (default) {
                        is Long -> longPreferencesKey(name)
                        is Int -> intPreferencesKey(name)
                        is Boolean -> booleanPreferencesKey(name)
                        is Float -> floatPreferencesKey(name)
                        else -> stringPreferencesKey(name)
                    }] ?: default
                }.first() as T
    }
}