===== 개요 =====
Android에서 설정 등을 기록하고 불러오는 기능을 말한다. 과거에 shared preference라는 이름으로 제공하던 api가
현재는 [[https://developer.android.com/topic/libraries/architecture/datastore?hl=ko|Datastore]]라는 이름으로 변경되었다.
===== 필요한 의존성 파일 =====
datastore api와, lifecycle api가 필요하다. 당음과 같다.
모듈단계의 그래들 파일에 다음의 의존성을 추가한다.
// DataStore
// Alternatively - use the following artifact without an Android dependency.
implementation("androidx.datastore:datastore-preferences:1.2.0-alpha01")
val lifecycle_version = "2.5.1"
implementation("androidx.lifecycle:lifecycle-runtime-compose:$lifecycle_version")
===== Datastore 클래스 Helper 클래스 만들기 =====
==== 1. 소스파일 ====
다음과 같이 헬퍼 클래스를 만들어서 읽기와 쓰기를 한다.
package com.dklaw.memorize.database
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.core.IOException
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
class DataStoreMemorize(private val context : Context) {
private val Context.dataStore : DataStore by preferencesDataStore(name = "appPreferences")
private val FILTER_ON = booleanPreferencesKey("FilterOn") // string 저장 키값
// Datastore 읽기
// Flow : coroutines.flow import 해야됨
val valueOfFilter : Flow = context.dataStore.data
.map {preferences ->
preferences[FILTER_ON] ?: false
}
// Datastore 쓰기
suspend fun setFilterSwitch(switch : Boolean){
context.dataStore.edit { preferences->
preferences[FILTER_ON] = switch
}
}
}
==== 2. 인스턴스 생성하기 ====
"appPreferences"란 이름의 Datastore 인스턴스를 다음과 같이 생성한다. Datastore는 한 앱당 하나의 인스턴스만 싱글톤으로 사용되어야 하므로 호출에 있어서는 굳이 이름이 필요 없을 것이다. 다만, 유지보수 관점에서 기존의 Datastore와는 다른 새로운 Datastore 인스턴스를 만들어야 할 필요도 있을 것이므로 이름은 필요할 것이다.
private val Context.dataStore : DataStore by preferencesDataStore(name = "appPreferences")
==== 3. 키값의 제목 설정하기 ====
Datastore는 [키, 밸류]의 쌍으로 데이터를 저장한다. 이를테면 C#의 Dictionary와 매우 비슷한 구조인 것이다.
즉, 각 키별로 형식이 존재한다. 이를테면 int값을 저장할 때에는 intPreferencesKey라고 하고, boolean값을 저장할 때에는 booleanPreferencesKey라고 한다.
우리는 boolean값을 "FILTER_ON" 이란 이름으로 저장할 것이다. 따라서 다음과 같이 키를 정의하게 된다.
private val FILTER_ON = booleanPreferencesKey("FilterOn") // string 저장 키값
===== 싱글턴으로 만들기 =====
===== 실제 compose내에서 사용하기