-
Notifications
You must be signed in to change notification settings - Fork 617
Migrate common from SharedPreferences to DataStore #6801
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
Open
daymxn
wants to merge
24
commits into
main
Choose a base branch
from
daymon-sharedpreferences-work
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+413
−135
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
a2020ac
Implement temp DataStore class
daymxn 58c97df
Migrate common
daymxn 77be82f
Update DataStore.kt
daymxn 12b56e7
Merge branch 'main' into daymon-sharedpreferences-work
daymxn 638eb67
Update HeartBeatInfoStorage.java
daymxn 417eda6
Merge branch 'main' into daymon-sharedpreferences-work
daymxn 697ed13
Update DataStore.kt
daymxn a00351d
Bump components to see if it fixes the crash
daymxn 1c756ee
Add logging to try to catch error.
daymxn 1b53a94
Add additional logging
daymxn 8459026
Make provider lazy
daymxn bdf4259
Merge branch 'main' into daymon-sharedpreferences-work
daymxn 09ac9c3
Update compile/target sdk versions in health metrics
daymxn 08aab02
Use version toml
daymxn 4dda28b
Update DataStore.kt
daymxn 5c004c5
Remove logging
daymxn 2826738
Merge branch 'main' into daymon-sharedpreferences-work
daymxn c7e34a9
Update firebase-common.gradle.kts
daymxn 607c417
Exclude datastore proto deps
daymxn 42824aa
Revert "Exclude datastore proto deps"
daymxn 66b6108
Merge branch 'main' into daymon-sharedpreferences-work
daymxn 9e143b5
Hide datastore from public api/add note on thread
daymxn 9ce5766
Update CHANGELOG.md
daymxn 5619a56
Merge branch 'main' into daymon-sharedpreferences-work
daymxn 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
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
236 changes: 236 additions & 0 deletions
236
firebase-common/src/main/java/com/google/firebase/datastore/DataStore.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,236 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.google.firebase.datastore | ||
|
||
import android.content.Context | ||
import androidx.datastore.core.DataStore | ||
import androidx.datastore.preferences.SharedPreferencesMigration | ||
import androidx.datastore.preferences.core.MutablePreferences | ||
import androidx.datastore.preferences.core.Preferences | ||
import androidx.datastore.preferences.core.edit | ||
import androidx.datastore.preferences.preferencesDataStore | ||
import com.google.firebase.annotations.concurrent.Background | ||
import kotlinx.coroutines.flow.firstOrNull | ||
import kotlinx.coroutines.runBlocking | ||
|
||
/** | ||
* Wrapper around [DataStore] for easier migration from `SharedPreferences` in Java code. | ||
* | ||
* Automatically migrates data from any `SharedPreferences` that share the same context and name. | ||
* | ||
* There should only ever be _one_ instance of this class per context and name variant. | ||
* | ||
* Note that most of the methods in this class **block** on the _current_ thread, as to help keep | ||
* parity with existing Java code. Typically, you'd want to dispatch this work to another thread | ||
* like [@Background][Background]. | ||
* | ||
* > Do **NOT** use this _unless_ you're bridging Java code. If you're writing new code, or your | ||
* code is in Kotlin, then you should create your own singleton that uses [DataStore] directly. | ||
* | ||
* Example: | ||
* ```java | ||
* DataStorage heartBeatStorage = new DataStorage(applicationContext, "FirebaseHeartBeat"); | ||
* ``` | ||
* | ||
* @property context The [Context] that this data will be saved under. | ||
* @property name What the storage file should be named. | ||
* | ||
* @hide | ||
*/ | ||
class DataStorage(val context: Context, val name: String) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we use a name like |
||
/** | ||
* Used to ensure that there's only ever one call to [editSync] per thread; as to avoid deadlocks. | ||
*/ | ||
private val editLock = ThreadLocal<Boolean>() | ||
|
||
private val Context.dataStore: DataStore<Preferences> by | ||
preferencesDataStore( | ||
name = name, | ||
produceMigrations = { listOf(SharedPreferencesMigration(it, name)) } | ||
) | ||
|
||
private val dataStore = context.dataStore | ||
|
||
/** | ||
* Get data from the datastore _synchronously_. | ||
* | ||
* Note that if the key is _not_ in the datastore, while the [defaultValue] will be returned | ||
* instead- it will **not** be saved to the datastore; you'll have to manually do that. | ||
* | ||
* Blocks on the currently running thread. | ||
* | ||
* Example: | ||
* ```java | ||
* Preferences.Key<Long> fireCountKey = PreferencesKeys.longKey("fire-count"); | ||
* assert dataStore.get(fireCountKey, 0L) == 0L; | ||
* | ||
* dataStore.putSync(fireCountKey, 102L); | ||
* assert dataStore.get(fireCountKey, 0L) == 102L; | ||
* ``` | ||
* | ||
* @param key The typed key of the entry to get data for. | ||
* @param defaultValue A value to default to, if the key isn't found. | ||
* | ||
* @see Preferences.getOrDefault | ||
*/ | ||
fun <T> getSync(key: Preferences.Key<T>, defaultValue: T): T = runBlocking { | ||
dataStore.data.firstOrNull()?.get(key) ?: defaultValue | ||
} | ||
|
||
/** | ||
* Checks if a key is present in the datastore _synchronously_. | ||
* | ||
* Blocks on the currently running thread. | ||
* | ||
* Example: | ||
* ```java | ||
* Preferences.Key<Long> fireCountKey = PreferencesKeys.longKey("fire-count"); | ||
* assert !dataStore.contains(fireCountKey); | ||
* | ||
* dataStore.putSync(fireCountKey, 102L); | ||
* assert dataStore.contains(fireCountKey); | ||
* ``` | ||
* | ||
* @param key The typed key of the entry to find. | ||
*/ | ||
fun <T> contains(key: Preferences.Key<T>): Boolean = runBlocking { | ||
dataStore.data.firstOrNull()?.contains(key) ?: false | ||
} | ||
|
||
/** | ||
* Sets and saves data in the datastore _synchronously_. | ||
* | ||
* Existing values will be overwritten. | ||
* | ||
* Blocks on the currently running thread. | ||
* | ||
* Example: | ||
* ```java | ||
* dataStore.putSync(PreferencesKeys.longKey("fire-count"), 102L); | ||
* ``` | ||
* | ||
* @param key The typed key of the entry to save the data under. | ||
* @param value The data to save. | ||
* | ||
* @return The [Preferences] object that the data was saved under. | ||
*/ | ||
fun <T> putSync(key: Preferences.Key<T>, value: T): Preferences = runBlocking { | ||
dataStore.edit { it[key] = value } | ||
} | ||
|
||
/** | ||
* Gets all data in the datastore _synchronously_. | ||
* | ||
* Blocks on the currently running thread. | ||
* | ||
* Example: | ||
* ```java | ||
* ArrayList<String> allDates = new ArrayList<>(); | ||
* | ||
* for (Map.Entry<Preferences.Key<?>, Object> entry : dataStore.getAllSync().entrySet()) { | ||
* if (entry.getValue() instanceof Set) { | ||
* Set<String> dates = new HashSet<>((Set<String>) entry.getValue()); | ||
* if (!dates.isEmpty()) { | ||
* allDates.add(new ArrayList<>(dates)); | ||
* } | ||
* } | ||
* } | ||
* ``` | ||
* | ||
* @return An _immutable_ map of data currently present in the datastore. | ||
*/ | ||
fun getAllSync(): Map<Preferences.Key<*>, Any> = runBlocking { | ||
dataStore.data.firstOrNull()?.asMap() ?: emptyMap() | ||
} | ||
|
||
/** | ||
* Transactionally edit data in the datastore _synchronously_. | ||
* | ||
* Edits made within the [transform] callback will be saved (committed) all at once once the | ||
* [transform] block exits. | ||
* | ||
* Because of the blocking nature of this function, you should _never_ call [editSync] within an | ||
* already running [transform] block. Since this can cause a deadlock, [editSync] will instead | ||
* throw an exception if it's caught. | ||
* | ||
* Blocks on the currently running thread. | ||
* | ||
* Example: | ||
* ```java | ||
* dataStore.editSync((pref) -> { | ||
* Long heartBeatCount = pref.get(HEART_BEAT_COUNT_TAG); | ||
* if (heartBeatCount == null || heartBeatCount > 30) { | ||
* heartBeatCount = 0L; | ||
* } | ||
* pref.set(HEART_BEAT_COUNT_TAG, heartBeatCount); | ||
* pref.set(LAST_STORED_DATE, "1970-0-1"); | ||
* | ||
* return null; | ||
* }); | ||
* ``` | ||
* | ||
* @param transform A callback to invoke with the [MutablePreferences] object. | ||
* | ||
* @return The [Preferences] object that the data was saved under. | ||
* @throws IllegalStateException If you attempt to call [editSync] within another [transform] | ||
* block. | ||
* | ||
* @see Preferences.getOrDefault | ||
*/ | ||
fun editSync(transform: (MutablePreferences) -> Unit): Preferences = runBlocking { | ||
if (editLock.get() == true) { | ||
throw IllegalStateException( | ||
""" | ||
Don't call DataStorage.edit() from within an existing edit() callback. | ||
This causes deadlocks, and is generally indicative of a code smell. | ||
Instead, either pass around the initial `MutablePreferences` instance, or don't do everything in a single callback. | ||
""" | ||
.trimIndent() | ||
) | ||
} | ||
editLock.set(true) | ||
try { | ||
dataStore.edit { transform(it) } | ||
} finally { | ||
editLock.set(false) | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Helper method for getting the value out of a [Preferences] object if it exists, else falling back | ||
* to the default value. | ||
* | ||
* This is primarily useful when working with an instance of [MutablePreferences] | ||
* - like when working within an [DataStorage.editSync] callback. | ||
* | ||
* Example: | ||
* ```java | ||
* dataStore.editSync((pref) -> { | ||
* long heartBeatCount = DataStoreKt.getOrDefault(pref, HEART_BEAT_COUNT_TAG, 0L); | ||
* heartBeatCount+=1; | ||
* pref.set(HEART_BEAT_COUNT_TAG, heartBeatCount); | ||
* | ||
* return null; | ||
* }); | ||
* ``` | ||
* | ||
* @param key The typed key of the entry to get data for. | ||
* @param defaultValue A value to default to, if the key isn't found. | ||
*/ | ||
fun <T> Preferences.getOrDefault(key: Preferences.Key<T>, defaultValue: T) = | ||
get(key) ?: defaultValue |
16 changes: 16 additions & 0 deletions
16
firebase-common/src/main/java/com/google/firebase/datastore/package-info.java
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,16 @@ | ||
// Copyright 2023 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
/** @hide */ | ||
package com.google.firebase.datastore; |
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.
Is this something we should try to enforce through code?