Skip to content

Commit

Permalink
#7 - Add DataStoreRepository to Data
Browse files Browse the repository at this point in the history
  • Loading branch information
kayraenezozenalp committed Oct 10, 2023
1 parent 5775ce5 commit 0785783
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions data/src/main/java/com/io1/data/datastore/DataStoreRepository.kt
Original file line number Diff line number Diff line change
@@ -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<Preferences> 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<Boolean> {
return dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
val onBoardingState = preferences[PreferencesKey.onBoardingKey] ?: false
onBoardingState
}
}
}

0 comments on commit 0785783

Please sign in to comment.