๐์ฐธ๊ณ ์๋ฃ
OnSharedPreferenceChangeListener
๋ก ์ฝ๋ฐฑ๋ง ๋ฐ์ ์ ์์commit()
์ด ์๋ apply()
๋ฅผ ํตํ ๋น๋๊ธฐ write ์ง์apply()
๋ ์ฆ์ ๋น๋๊ธฐ ํธ์ถ Xfsync()
native ํจ์๋ ๋ฉ์ธ ์ฐ๋ ๋ ๋ธ๋กํจcommit()
ํจ์SharedPreferences
DataStore์ ์ข ๋ฅ
protocol buffers
๋ฅผ ์ฌ์ฉํ์ฌ schema๋ฅผ ์ ์ํด์ผ ํจDataStore๋ฅผ ์ฌ์ฉํ ๋ ์ง์ผ์ผํ ๊ฒ
SinglePrecessDataStore
๊ณผ MultiProcessDataStore
ํผ์ฉ XDataStore
ํด๋์ค์ Preferences
ํด๋์ค ์ฌ์ฉ dependencies {
// Preferences DataStore (SharedPreferences like APIs)
implementation "androidx.datastore:datastore-preferences:1.1.1"
}
preferencesDataStore
์ property delegate ์ฌ์ฉDataStore<Preferences>
ํ์
์ ์ธ์คํด์ค ์์ฑ// At the top level of your kotlin file:
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
DataStore.data
ํ๋กํผํฐ ์ฌ์ฉFlow
๋ก ์ฝ์ด์์ง// key for an int value
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
val exampleCounterFlow: Flow<Int> = context.dataStore.data
.map { preferences ->
preferences[EXAMPLE_COUNTER] ?: 0 // No type safety
}
edit
ํจ์ ์ฌ์ฉํ์ฌ ๊ฐ update ๊ฐ๋ฅsuspend fun DataStore<Preferences>.edit(
transform: suspend (MutablePreferences) -> Unit
): Preferences
suspend fun incrementCounter() {
context.dataStore.edit { settings ->
val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
settings[EXAMPLE_COUNTER] = currentCounterValue + 1
}
}