Skip to content

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
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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 Mar 24, 2025
58c97df
Migrate common
daymxn Mar 24, 2025
77be82f
Update DataStore.kt
daymxn Mar 24, 2025
12b56e7
Merge branch 'main' into daymon-sharedpreferences-work
daymxn Mar 24, 2025
638eb67
Update HeartBeatInfoStorage.java
daymxn Mar 25, 2025
417eda6
Merge branch 'main' into daymon-sharedpreferences-work
daymxn Mar 25, 2025
697ed13
Update DataStore.kt
daymxn Mar 25, 2025
a00351d
Bump components to see if it fixes the crash
daymxn Mar 25, 2025
1c756ee
Add logging to try to catch error.
daymxn Mar 25, 2025
1b53a94
Add additional logging
daymxn Mar 26, 2025
8459026
Make provider lazy
daymxn Mar 26, 2025
bdf4259
Merge branch 'main' into daymon-sharedpreferences-work
daymxn Mar 27, 2025
09ac9c3
Update compile/target sdk versions in health metrics
daymxn Mar 27, 2025
08aab02
Use version toml
daymxn Mar 27, 2025
4dda28b
Update DataStore.kt
daymxn Mar 27, 2025
5c004c5
Remove logging
daymxn Mar 27, 2025
2826738
Merge branch 'main' into daymon-sharedpreferences-work
daymxn Apr 10, 2025
c7e34a9
Update firebase-common.gradle.kts
daymxn Apr 10, 2025
607c417
Exclude datastore proto deps
daymxn Apr 10, 2025
42824aa
Revert "Exclude datastore proto deps"
daymxn Apr 10, 2025
66b6108
Merge branch 'main' into daymon-sharedpreferences-work
daymxn Jun 6, 2025
9e143b5
Hide datastore from public api/add note on thread
daymxn Jun 9, 2025
9ce5766
Update CHANGELOG.md
daymxn Jun 9, 2025
5619a56
Merge branch 'main' into daymon-sharedpreferences-work
daymxn Jun 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions firebase-common/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Unreleased
* [fixed] Correctly declare dependency on firebase-components, issue #5732
* [changed] Added extension method `Random.nextAlphanumericString()` (PR #5818)
* [changed] Migrated internal `SharedPreferences` usages to `DataStore`. ([GitHub PR #6801](https://github.com/firebase/firebase-android-sdk/pull/6801){ .external})

# 20.4.0
* [changed] Added Kotlin extensions (KTX) APIs from `com.google.firebase:firebase-common-ktx`
Expand Down
1 change: 1 addition & 0 deletions firebase-common/firebase-common.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dependencies {

api("com.google.firebase:firebase-components:18.0.0")
api("com.google.firebase:firebase-annotations:16.2.0")
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.annotation)
implementation(libs.androidx.futures)
implementation(libs.kotlin.stdlib)
Expand Down
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.
Copy link
Collaborator

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?

*
* 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) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use a name like DataStorageForJava, JavaDataStorage, DataStorageJavaAdapter, or the like to make it even more clear that this is intended for Java only? Since this is not meant to be part of the public API we can go with ugly but clearer naming

/**
* 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
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;
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.google.firebase.annotations.concurrent.Background;
import com.google.firebase.components.Component;
import com.google.firebase.components.Dependency;
import com.google.firebase.components.Lazy;
import com.google.firebase.components.Qualified;
import com.google.firebase.inject.Provider;
import com.google.firebase.platforminfo.UserAgentPublisher;
Expand Down Expand Up @@ -116,7 +117,7 @@ private DefaultHeartBeatController(
Provider<UserAgentPublisher> userAgentProvider,
Executor backgroundExecutor) {
this(
() -> new HeartBeatInfoStorage(context, persistenceKey),
new Lazy<>(() -> new HeartBeatInfoStorage(context, persistenceKey)),
consumers,
backgroundExecutor,
userAgentProvider,
Expand Down
Loading