pref: 优化 DataStore

This commit is contained in:
HuanCheng65 2023-03-10 14:39:20 +08:00
parent a311f75327
commit 0912962f0e
No known key found for this signature in database
GPG Key ID: E9031EF91A805148
1 changed files with 26 additions and 19 deletions

View File

@ -22,7 +22,8 @@ object DataStoreConst {
const val DATA_STORE_NAME = "app_preferences" const val DATA_STORE_NAME = "app_preferences"
} }
val Context.dataStore: DataStore<Preferences> by preferencesDataStore( private val dataStoreInstance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
preferencesDataStore(
name = DataStoreConst.DATA_STORE_NAME, name = DataStoreConst.DATA_STORE_NAME,
produceMigrations = { context -> produceMigrations = { context ->
listOf( listOf(
@ -43,10 +44,16 @@ val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
) )
} }
) )
}
val Context.dataStore: DataStore<Preferences> by dataStoreInstance
@SuppressLint("FlowOperatorInvokedInComposition") @SuppressLint("FlowOperatorInvokedInComposition")
@Composable @Composable
fun <T> DataStore<Preferences>.collectPreferenceAsState(key: Preferences.Key<T>, defaultValue: T): State<T> { fun <T> DataStore<Preferences>.collectPreferenceAsState(
key: Preferences.Key<T>,
defaultValue: T
): State<T> {
return data.map { it[key] ?: defaultValue }.collectAsState(initial = defaultValue) return data.map { it[key] ?: defaultValue }.collectAsState(initial = defaultValue)
} }