개발/Android

Data store vs Shared preference

이도일 2023. 10. 23. 13:22

DataStore

SharedPreference는 동기적으로 동작. 특히 이의 apply()는 ui스레드를 차단하여 잠재적인 성능 문제를야기할 수 있음 → 대안책

  1. Dispatchers.IO 옵션을 사용하면 ui스레드 안전성을 보장받을 수 있음

Proto DataStore

  • 코루틴과 플로우를 활용함

Preferences DataStore

  • 키-밸류 쌍 관리
  • sharedPreferencs의 완벽한 대응책

Interface DataStoreAPI

interface DataStoreAPI {
    suspend fun <T> getPreferenceValue(key: Preferences.Key<T>,defaultValue: T):T
    suspend fun <T> putPreferenceValue(key: Preferences.Key<T>,value:T)
    suspend fun <T> getPreferenceFlow(key: Preferences.Key<T>, defaultValue: T): Flow<T>
    suspend fun <T> removePreference(key: Preferences.Key<T>)
    suspend fun <T> clearPreference()
}

object DataStoreConstants

object DataStoreConstants {
    val USER_ID = stringPreferencesKey("userId")
    val USER_NUMBER = longPreferencesKey("mobile_number")
    val IS_EXISTING_USER = booleanPreferencesKey("existing_user")
    val AGE = intPreferencesKey("age")
}

DataStoreManager

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = "MyDataStore")

SharedPreference에서의 마이그레이션은 이렇게

private  val Context.dataStore: referenceDataStore(     name = "MyDataStore" ,     producerMigrations = ::sharedPreferencesMigration ) 에 의한 DataStore<Preferences>

For ViewModel…

// Fetching data via Flow
viewModelScope.launch {
    DataStoreManager(context).getUserId().collect {

    }
}

// Fetching data via static method
viewModelScope.launch {
   val userId =  DataStoreManager(context).getUserId()
}

// Saving Data
val userId = "6tqfe354gd"
viewModelScope.launch {
    DataStoreManager(context).saveUserId(userId)
}

For Activity/Fragment…

// Fetching data via Flow
lifecycleScope.launch {
    DataStoreManager(context).isExistingUser().collect {

    }
}

// Fetching data via static method
lifecycleScope.launch {
   val existingUser =  DataStoreManager(context).isExistingUser()
}

// Saving Data
lifecycleScope.launch {
    DataStoreManager(context).saveExistingUser(true)
}

Uploaded by N2T