pref: 优化 DataStore
This commit is contained in:
parent
a311f75327
commit
0912962f0e
|
|
@ -22,7 +22,8 @@ object DataStoreConst {
|
|||
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,
|
||||
produceMigrations = { context ->
|
||||
listOf(
|
||||
|
|
@ -42,11 +43,17 @@ val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
|||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
val Context.dataStore: DataStore<Preferences> by dataStoreInstance
|
||||
|
||||
@SuppressLint("FlowOperatorInvokedInComposition")
|
||||
@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)
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue