DataStore

BongKu·2023년 6월 22일
0

Android

목록 보기
9/30
post-thumbnail

DataStore ?

Jetpack 라이브러리로, 경량화된 데이터 저장소를 제공하는 기술입니다. 키-값 쌍 또는 유형이 지정된 객체를 저장할 수 있습니다.

DataStore는 Preferences DataStore와 Proto DataStore 두 가지 구현을 제공합니다.

  • Preferences DataStore : 키를 사용하여 데이터를 저장하고 데이터에 액세스합니다. 사전 정의된 스키마가 필요합니다.
  • Proto DataStore : 맞춤 데이터 유형의 인스턴스로 데이터를 저장하며, 스키마를 사전 정의 해야합니다.
💡 다음 규칙을 항상 유의하세요
  1. 같은 프로세스에서 특정 파일의 DataStore 인스턴스를 두 개 이상 만들지 않습니다.
  2. DataStore의 일반 유형은 변경 불가능해야 합니다.
  3. 동일한 파일에서 SingleProcessDataStoreMultiProcessDataStore를 함께 사용하지 않습니다. (둘 이상의 프로세스에서 DataStore에 액세스하려면 항상 MultiProcessDataStore를 사용하세요

Preferences DataStore 사용 예제

개발자 문서의 내용과 실제 프로젝트 사용 예시로 알아보겠습니다.

1. Gradle 파일에 dependency 추가

    // 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")
    }
    

2. Preferences DataStore 만들기

<개발자 문서>

// 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 파일의 최상위 수준에서 인스턴스를 한 번 호출한 후 나머지 부분에서는 이 속성을 통해 인스턴스에 액세스합니다.

3. Preferences Datastore에서 읽기

<개발자 문서>

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를 사용했습니다.

3. Preferences DataStore에 쓰기

<개발자 문서>

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

profile
화이팅

0개의 댓글