• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    미해결

DataStoreEx 파트 class MyDataStore(context: Context) { 수정 제안)

23.12.05 20:33 작성 23.12.05 20:42 수정 조회수 197

0

기존 : 지역 변수

DataStoreEx 파트 class MyDataStore {

...

 

private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")

...

}

제안 : 전역 변수로 변경

private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")

DataStoreEx 파트 class MyDataStore {

...

}

 

위 내용을 코딩중 Context.dataStore은 전역 변수 또는 싱글톤으로 제작 해야 안정적으로 보입니다 .

 

예를 들어서 Activity안에 위 클래스를 생성하는 코드를 작성한 후 동작 하면 일단은 동작 합니다.

하지만 다시 Activity에 진입하면 에러가 납니다.

DataStore version 1.0.0입니다.

 

왜 그런지 찾아 보니

버전 1.0.0-alpha07

2021년 2월 24일

androidx.datastore:datastore-*:1.0.0-alpha07이 출시되었습니다. 버전 1.0.0-alpha07에 포함된 커밋을 확인하세요.

API 변경사항

  • Context.createDataStore 확장 함수를 삭제하고 globalDataStore 속성 위임으로 대체했습니다. kotlin 파일의 최상위 수준에서 globalDataStore를 한 번 호출합니다. 예:

    val Context.myDataStore by dataStore(...)
    

    kotlin 파일의 최상위 수준에 배치하면 이 인스턴스가 하나만 생깁니다. (I57215, b/173726702)

  • RxDataStore 함수는 이제 DataStore의 확장 함수 대신 RxDataStore 클래스에 있습니다. (Idccdb, b/177691248)

  • EncryptedSharedPreferences를 DataStore로 이전(또는 SharedPreferences를 직접 부팅)하려는 경우 이제 SharedPreferences를 삽입할 수 있는 새로운 SharedPreferencesMigration 생성자를 사용하면 됩니다. (I8e04e, b/177278510)

  • ================================

버그 수정

  • 동일한 파일에 활성 DataStore가 여러 개 있는 경우 이제 DataStore에서 예외가 발생합니다. DataStore를 싱글톤으로 관리하지 않았거나 한 파일의 DataStore 인스턴스 두 개가 동시에 활성화되지 않도록 조치하지 않은 경우 이제 DataStore를 읽거나 DataStore에 쓸 때 예외가 발생할 수도 있습니다. DataStore를 싱글톤으로 관리하면 해결할 수 있습니다. (Ib43f4, b/177691248)

  • 호출자 범위 취소 시의 취소 동작을 수정합니다. (I2c7b3)

 

라고 적혀 있네요 ...

 

그래서 전 Context.myDataStore를 전역 변수로 수정하고 테스트 했는데 정상적으로 동작 되는것을 확인 했습니다.

 

이상입니다.

답변 3

·

답변을 작성해보세요.

1

Sim Seon Bo님의 프로필

Sim Seon Bo

2024.04.25

좋은 글이네요.

companion object {
    private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")
}

0

just kim님의 프로필

just kim

질문자

2023.12.05

class MyDataStore(context : Context {

private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")

=> 에서

private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")

class MyDataStore(context : Context {

Context.dataStore 를 class밖으로 뺐어요 ...

 

의견 감사합니다.

다음 업데이트에 object 형태로 싱글톤으로 이용하는 형태로 변경하겠습니다!

0

안녕하세요

좋은 제안 주셔서 감사합니다.

해당 부분 다시 확인해보겠습니다.

(사실 프레퍼런스나 유틸 종류는 싱글톤으로 저도 많이 사용하긴 합니다만, 예제다 보니 이렇게..)

 

그런데 제안주신 부분이

 

기존

private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")

제안

private val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_pref")

이렇게 똑같이 말씀주셨는데 혹시 어떻게 변경하셨는지 알 수 있을까요?