0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

preferenceDataStore実装方法

0
Posted at

はじめに

今回はSharedPreferenceの代わりとなるpreferenceDataSoterの実装方法を紹介してきます

実装

// まずはデータストレージを作成
private const val PREFERENCES_NAME = "preference"
private val Context.dataStore by preferencesDataStore(PREFERENCES_NAME)

@Singleton
internal class DataStore @Inject constructor(
    @ApplicationContext context: Context,
    @ApplicationScope private val externalScope: CoroutineScope,
) {
    private val dataStore = context.dataStore

    private val dataFlow = dataStore.data
        .catch { ex -> throw ex }
        .map { preference ->
            val data = preference[KEY] ?: return@map null
            DataClass(data = data)
        }
        .stateIn(externalScope, SharingStarted.Eagerly, null)

    fun getDataFlow(): Flow<DataClass?> = dataFlow

    fun saveData(data: DataClass) {
        externalScope.launch {
            dataStore.edit { prefs ->
                prefs[KEY] = data.data
            }
        }
    }

    companion object {
    // 型によってstringPreferencesKeyになったりする
        private val KEY = booleanPreferencesKey("key")
    }
}

最後に

大まかではありますが、上記を参考にすればたいていは作れるかと思います
どなたかのお役に立てれば幸いです

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?