일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- Dialog
- textview
- 앱
- drift
- CustomScrollView
- android
- ScrollView
- Button
- Kotlin
- Navigation
- DART
- activity
- 계측
- data
- tabbar
- LifeCycle
- appbar
- Flutter
- TEST
- binding
- Coroutines
- textfield
- Compose
- livedata
- viewmodel
- scroll
- intent
- 안드로이드
- 테스트
- 앱바
- Today
- Total
Study Record
[안드로이드] DataSotre (SharedPreferences 대체) 본문
😶 DataStore 개요
DataStore 는 SharedPreferences 를 대체하는 것을 목표로 한 향상된 데이터 저장 솔루션으로 나온 Android Jetpack 라이브러리이다. Coroutines 과 Flow 를 사용하여 데이터를 비동기적으로 일관성있게 읽고 저장한다.
DataStore 는 Preferences DataStore 와 Proto DataStore 으로 나뉜다.
Preferences DataStore 는 key 를 이용하여 데이터에 접근하고 저장한다. 타입 안전성을 보장하지 않는다.
Proto DataStore 는 커스텀한 데이터 타입을 가진 객체로 데이터를 저장한다. Protocol buffers 를 사용하며, 스키마를 정의해야하지만 타입 안전성을 보장한다.
dependency 추가하기
dependencies {
implementation "androidx.datastore:datastore-preferences:1.0.0"
}
😶 Preferences DataStore
Preferences DataStore 는 key-value 방식으로 데이터를 접근하고 저장한다. 먼저, preferencesDataStore 라는 delegate 를 사용하여 DataStore 객체를 선언한다. Preferences 은 데이터에 대한 key 가 필요하다. key 는 key Function 으로 얻을 수 있는데 데이터의 타입이 Boolean, Int, String 에 따라 booleanPreferencesKey(), intPreferencesKey(), stringPreferencesKey() 을 사용할 수 있다.
private const val PREFERENCES_NAME = "preferences_name"
class SettingsDataStore(context: Context) {
private val Context.dataStore : DataStore<Preferences> by preferencesDataStore(
name = PREFERENCES_NAME
)
// Key Function
private val IS_PREFERENCES_VALUE = booleanPreferencesKey("is_preferences_value")
// private val INT_PREFERENCES_VALUE = intPreferencesKey("int_preferences_value")
// private val STRING_PREFERENCES_VALUE = stringPreferencesKey("string_preferences_value")
}
데이터 접근 & 저장
예시는 데이터 타입이 Boolean 이다.
private const val PREFERENCES_NAME = "preferences_name"
class SettingsDataStore(context: Context) {
private val Context.dataStore : DataStore<Preferences> by preferencesDataStore(
name = PREFERENCES_NAME
)
private val IS_PREFERENCES_VALUE = booleanPreferencesKey("is_preferences_value")
// 데이터 접근 - 데이터 타입은 Boolean
val preferenceFlow: Flow<Boolean> = context.dataStore.data
.catch {
if (it is IOException) {
it.printStackTrace()
emit(emptyPreferences())
} else {
throw it
}
}
.map { preferences ->
preferences[IS_PREFERENCES_VALUE] ?: true
}
// 데이터 저장
suspend fun saveLayoutToPreferencesStore(isPreferencesValue: Boolean, context: Context) {
context.dataStore.edit { preferences ->
preferences[IS_PREFERENCES_VALUE] = isLinearLayoutManager
}
}
}
다음은 Fragment/Activity 에서 DataStore 클래스를 접근하여 데이터를 가져오고 저장하는 방법이다.
class LetterListFragment : Fragment() {
private lateinit var SettingsDataStore: SettingsDataStore
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Initialize SettingDataStore
SettingsDataStore = SettingsDataStore(requireContext())
SettingsDataStore.preferenceFlow.asLiveData().observe(this.viewLifecycleOwner) { value ->
// 데이터 값이 변경될 때마다 호출된다. (value)
}
}
// 데이터 저장하기
fun saveData(value: Boolean) {
lifecycle.coroutineScope.launch() {
SettingsDataStore.saveLayoutToPreferencesStore(value, requireContext())
}
}
}
앱 아키텍처: 데이터 영역 - Datastore - Android 개발자 | Android Developers
데이터 영역 라이브러리에 관한 이 앱 아키텍처 가이드를 통해 Preferences DataStore 및 Proto DataStore, 설정 등을 알아보세요.
developer.android.com
DataStore | Android Developers
androidx.appsearch.builtintypes.properties
developer.android.com
Prefer Storing Data with Jetpack DataStore
News and insights on the Android platform, developer tools, and events.
android-developers.googleblog.com
'안드로이드' 카테고리의 다른 글
[Android] 앱 아키텍처 (0) | 2023.08.25 |
---|---|
[안드로이드] Repository pattern 과 Caching (0) | 2023.08.21 |
[안드로이드] Room (database) 살펴보기 (ViewModel, Flow, ListAdapter, LiveData, Coroutines) (0) | 2023.08.19 |
[안드로이드] RecyclerView ListAdapter 살펴보기 (0) | 2023.08.10 |
[안드로이드] binding Adapter (결합 어댑터) (0) | 2023.08.10 |