-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#7 - Add DataStoreRepository to Data
- Loading branch information
1 parent
5775ce5
commit 0785783
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
data/src/main/java/com/io1/data/datastore/DataStoreRepository.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
} |