-
Notifications
You must be signed in to change notification settings - Fork 0
Migrate from SharedPreferences to DataStore #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
104 changes: 104 additions & 0 deletions
104
app/src/main/kotlin/app/futured/androidprojecttemplate/data/persistence/JsonPersistence.kt
This file contains hidden or 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,104 @@ | ||
| package app.futured.androidprojecttemplate.data.persistence | ||
|
|
||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.core.edit | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.firstOrNull | ||
| import kotlinx.coroutines.flow.map | ||
| import kotlinx.serialization.SerializationException | ||
| import kotlinx.serialization.encodeToString | ||
| import kotlinx.serialization.json.Json | ||
| import timber.log.Timber | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
|
|
||
| /** | ||
| * [DataStore]-backed Persistence which allows storage and observing of complex JSON objects. | ||
| * Uses [kotlinx.serialization] to serialize and deserialize objects into Strings. | ||
| */ | ||
| @Singleton | ||
| class JsonPersistence @Inject constructor( | ||
| val dataStore: DataStore<Preferences>, | ||
| val json: Json, | ||
| ) { | ||
|
|
||
| /** | ||
| * Saves provided [value] in persistence under provided [key]. | ||
| */ | ||
| suspend inline fun <reified T : Any> save( | ||
| key: Preferences.Key<String>, | ||
| value: T, | ||
| ) { | ||
| dataStore.edit { preferences -> preferences[key] = json.encodeToString<T>(value) } | ||
| } | ||
|
|
||
| /** | ||
| * Returns persisted object with provided [key]. | ||
| * | ||
| * @return Persisted object, or `null` if does not exist. | ||
| * @throws [SerializationException] if object could not be deserialized as [T]. | ||
| */ | ||
| suspend inline fun <reified T : Any> get(key: Preferences.Key<String>): T? = | ||
| dataStore.data.firstOrNull() | ||
| ?.let { preferences -> preferences[key] } | ||
| ?.let { jsonString -> | ||
| json.decodeFromString<T>(jsonString) | ||
| } | ||
|
|
||
| /** | ||
| * Returns a [Flow] of persisted objects with provided [key]. | ||
| * | ||
| * @return [Flow] of objects. Values in [Flow] can be `null` if not found in persistence. | ||
| * @throws [SerializationException] if object could not be deserialized as [T]. | ||
| */ | ||
| inline fun <reified T : Any> observe(key: Preferences.Key<String>): Flow<T?> = | ||
| dataStore.data | ||
| .map { preferences -> preferences[key] } | ||
| .map { jsonString -> | ||
| jsonString?.let { json.decodeFromString(jsonString) } | ||
| } | ||
|
|
||
| /** | ||
| * Removes persisted object with provided [key]. | ||
| */ | ||
| suspend fun delete(key: Preferences.Key<String>) = dataStore.edit { preferences -> preferences.remove(key) } | ||
|
|
||
| /** | ||
| * Returns persisted object with provided [key], catching any [SerializationException]s and mapping them to `null`. | ||
| * | ||
| * @return Persisted object, or `null` if does not exist or object cannot be deserialized as [T]. | ||
| */ | ||
| suspend inline fun <reified T : Any> getCatching(key: Preferences.Key<String>): T? = | ||
| runCatching { get<T>(key) } | ||
| .recoverCatching { error -> | ||
| if (error is SerializationException) { | ||
| Timber.tag("JsonPersistence").e(error, "Unable to deserialize property with key '${key.name}'") | ||
| null | ||
| } else { | ||
| throw error | ||
| } | ||
| } | ||
| .getOrThrow() | ||
|
|
||
| /** | ||
| * Returns a [Flow] of persisted objects with provided [key], catching any [SerializationException]s that might occur | ||
| * and mapping them to `null` values. | ||
| * | ||
| * @return [Flow] of objects. Values in [Flow] can be `null` if not found in persistence or cannot be deserialized as [T]. | ||
| */ | ||
| inline fun <reified T : Any> observeCatching(key: Preferences.Key<String>): Flow<T?> = | ||
| dataStore.data | ||
| .map { preferences -> preferences[key] } | ||
| .map { jsonString -> | ||
| runCatching { jsonString?.let { json.decodeFromString<T>(jsonString) } } | ||
| .recoverCatching { error -> | ||
| if (error is SerializationException) { | ||
| Timber.tag("JsonPersistence").e(error, "Unable to deserialize property with key '${key.name}'") | ||
| null | ||
| } else { | ||
| null | ||
| } | ||
| }.getOrThrow() | ||
| } | ||
| } |
46 changes: 0 additions & 46 deletions
46
app/src/main/kotlin/app/futured/androidprojecttemplate/data/persistence/Persistence.kt
This file was deleted.
Oops, something went wrong.
35 changes: 35 additions & 0 deletions
35
...c/main/kotlin/app/futured/androidprojecttemplate/data/persistence/PrimitivePersistence.kt
This file contains hidden or 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,35 @@ | ||
| package app.futured.androidprojecttemplate.data.persistence | ||
|
|
||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.core.edit | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.firstOrNull | ||
| import kotlinx.coroutines.flow.mapNotNull | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
|
|
||
| /** | ||
| * [DataStore]-backed Persistence which allows storage and observing of persisted entities. | ||
| */ | ||
| @Singleton | ||
| class PrimitivePersistence @Inject constructor( | ||
| private val dataStore: DataStore<Preferences>, | ||
| ) { | ||
|
|
||
| suspend fun <T : Any> get(key: Preferences.Key<T>): T? = dataStore.data.firstOrNull()?.run { | ||
| this[key] | ||
| } | ||
|
|
||
| fun <T : Any> observe(key: Preferences.Key<T>): Flow<T> = dataStore.data.mapNotNull { | ||
| it[key] | ||
| } | ||
|
|
||
| suspend fun <T : Any> save(key: Preferences.Key<T>, value: T) { | ||
| dataStore.edit { it[key] = value } | ||
| } | ||
|
|
||
| suspend fun delete(key: Preferences.Key<*>) = dataStore.edit { | ||
| it.remove(key) | ||
| } | ||
| } |
This file contains hidden or 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
This file contains hidden or 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
9 changes: 9 additions & 0 deletions
9
app/src/main/kotlin/app/futured/androidprojecttemplate/tools/extensions/ContextExtensions.kt
This file contains hidden or 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,9 @@ | ||
| package app.futured.androidprojecttemplate.tools.extensions | ||
|
|
||
| import android.content.Context | ||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.preferencesDataStore | ||
| import app.futured.androidprojecttemplate.tools.Constants | ||
|
|
||
| val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = Constants.DataStore.DEFAULT_DATASTORE_NAME) | ||
This file contains hidden or 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
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This extension is only used to create a datastore in Hilt module, and could be potentially misused by user to create a new datastore instead of injecting it. I would remove this and implement everything inside ApplicationModule, or at least move it to the ApplicationModule file and make it private.