안드로이드 DataStore에 대해서 알아보겠습니다.
implementation("androidx.datastore:datastore-preferences:1.0.0")
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"
class TestActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
val userManager = UserManager(applicationContext)
lifecycleScope.launch{
for(i in 0..10) {
delay(1000)
userManager.insertData()
userManager.getData()
}
}
val end = findViewById<Button>(R.id.end)
end.setOnClickListener {
finish()
}
}
}
class UserManager(context : Context) {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("user_pref")
private val mDataStore: DataStore<Preferences> = context.dataStore
val USER_NAME_KEY = stringPreferencesKey("USER_NAME")
suspend fun insertData() {
mDataStore.edit { preferences ->
preferences[USER_NAME_KEY] = "abc"
}
}
suspend fun getData(){
mDataStore.edit { preferences ->
val currentCounterValue = preferences[USER_NAME_KEY] ?: "null"
Log.e("UserManager ", currentCounterValue)
}
}
}
- 참조
https://developer.android.com/topic/libraries/architecture/coroutines?hl=ko
https://www.youtube.com/watch?v=xZV3RUtp9b4
https://jizard.tistory.com/213
https://developer.android.com/topic/libraries/architecture/datastore?hl=ko
https://developer.android.com/codelabs/android-preferences-datastore?hl=ko#1
'Android Jetpack' 카테고리의 다른 글
Simple Paging3 (0) | 2022.12.24 |
---|---|
dataStore - 2 (0) | 2022.08.15 |
BindingAdapter + databinding (0) | 2022.08.05 |
ROOM TypeConverter (0) | 2022.07.23 |
ROOM Embeded (0) | 2022.07.22 |