pref: 优化 DataStore
This commit is contained in:
parent
a311f75327
commit
0912962f0e
|
|
@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue