DataStore ?
Jetpack 라이브러리로, 경량화된 데이터 저장소를 제공하는 기술입니다. 키-값 쌍 또는 유형이 지정된 객체를 저장할 수 있습니다.
DataStore는 Preferences DataStore와 Proto DataStore 두 가지 구현을 제공합니다.
DataStore
인스턴스를 두 개 이상 만들지 않습니다.SingleProcessDataStore
와 MultiProcessDataStore
를 함께 사용하지 않습니다. (둘 이상의 프로세스에서 DataStore
에 액세스하려면 항상 MultiProcessDataStore
를 사용하세요Preferences DataStore 사용 예제
개발자 문서의 내용과 실제 프로젝트 사용 예시로 알아보겠습니다.
// Preferences DataStore (SharedPreferences like APIs)
dependencies {
implementation("androidx.datastore:datastore-preferences:1.0.0")
// Alternatively - use the following artifact without an Android dependency.
dependencies {
implementation("androidx.datastore:datastore-preferences-core:1.0.0")
}
// At the top level of your kotlin file:
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
class MyDataStore {
private val context = App.context()
companion object{
private val Context.dataStore:DataStore<Preferences> by preferencesDataStore("user")
}
}
DataStore<Preferences>
의 인스턴스를 만듭니다. kotlin 파일의 최상위 수준에서 인스턴스를 한 번 호출한 후 나머지 부분에서는 이 속성을 통해 인스턴스에 액세스합니다.
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
val exampleCounterFlow: Flow<Int> = context.dataStore.data
.map { preferences ->
// No type safety.
preferences[EXAMPLE_COUNTER] ?: 0
}
private val mDataStore:DataStore<Preferences> = context.dataStore
private val FIRSTACCESS_FLAG = booleanPreferencesKey("FIRSTACCESS_FLAG")
suspend fun getFirstData(): Boolean {
var currentValue = false
mDataStore.edit { preferences ->
currentValue = preferences[FIRSTACCESS_FLAG] ?: false
}
return currentValue
}
Preferences DataStore는 사전 정의된 스키마를 사용하지 않으므로 인스턴스에 저장해야 하는 각 값의 키를 정의하려면 상응하는 키 유형 함수
를 사용해야 합니다. 위 예시에서는 boolean 값을 저장하기 때문에 booleanPreferencesKey
를 사용했습니다.
suspend fun incrementCounter() {
context.dataStore.edit { settings ->
val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
settings[EXAMPLE_COUNTER] = currentCounterValue + 1
}
}
suspend fun setUpFirstData() {
mDataStore.edit { preferences ->
preferences[FIRSTACCESS_FLAG] = true
}
}
데이터를 트랜잭션 방식으로 업데이트하는 edit()
함수를 사용합니다.
참고
https://developer.android.com/topic/libraries/architecture/datastore?hl=ko