diff --git a/data/src/main/java/com/io1/data/datastore/DataStoreRepository.kt b/data/src/main/java/com/io1/data/datastore/DataStoreRepository.kt new file mode 100644 index 0000000..2790a21 --- /dev/null +++ b/data/src/main/java/com/io1/data/datastore/DataStoreRepository.kt @@ -0,0 +1,46 @@ +package com.io1.data.datastore + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.emptyPreferences +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.map +import java.io.IOException + +val Context.dataStore: DataStore by preferencesDataStore(name = "on_boarding_pref") + + +class DataStoreRepository(context: Context) { + + private object PreferencesKey { + val onBoardingKey = booleanPreferencesKey(name = "on_boarding_completed") + } + + private val dataStore = context.dataStore + + suspend fun saveOnBoardingState(completed: Boolean) { + dataStore.edit { preferences -> + preferences[PreferencesKey.onBoardingKey] = completed + } + } + + fun readOnBoardingState(): Flow { + return dataStore.data + .catch { exception -> + if (exception is IOException) { + emit(emptyPreferences()) + } else { + throw exception + } + } + .map { preferences -> + val onBoardingState = preferences[PreferencesKey.onBoardingKey] ?: false + onBoardingState + } + } +} \ No newline at end of file