diff --git a/lawnchair/src/app/lawnchair/preferences2/PreferenceManager2.kt b/lawnchair/src/app/lawnchair/preferences2/PreferenceManager2.kt index b6e7ff9a30..790c728792 100644 --- a/lawnchair/src/app/lawnchair/preferences2/PreferenceManager2.kt +++ b/lawnchair/src/app/lawnchair/preferences2/PreferenceManager2.kt @@ -85,6 +85,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking @LauncherAppSingleton @@ -118,6 +119,21 @@ class PreferenceManager2 @Inject constructor( fun getCachedPreferences(): Preferences = cachedPreferences + /** + * Runs [block] on the main thread once the cache has every value written so far. A preference's + * onSet runs right after its DataStore write, but the cache is updated by its own collector, + * which may not have run yet: refresh it from the DataStore, which already has the new value. + * If the collector stores a newer value while the read is suspended, that value is kept. + */ + internal fun withFreshCache(block: () -> Unit) { + scope.launch { + val cacheBeforeRead = cachedPreferences + val freshPreferences = preferencesDataStore.data.first() + if (cachedPreferences === cacheBeforeRead) cachedPreferences = freshPreferences + block() + } + } + private val reloadHelper = ReloadHelper(context) val darkStatusBar = preference( diff --git a/lawnchair/src/app/lawnchair/preferences2/ReloadHelper.kt b/lawnchair/src/app/lawnchair/preferences2/ReloadHelper.kt index 642a4d95d1..a02a0f2cfd 100644 --- a/lawnchair/src/app/lawnchair/preferences2/ReloadHelper.kt +++ b/lawnchair/src/app/lawnchair/preferences2/ReloadHelper.kt @@ -33,7 +33,9 @@ class ReloadHelper(private val context: Context) { private val tisBinder = TISBindHelper(context) { tis = it } fun reloadGrid() { - idp.onPreferencesChanged(context) + // The grid reads the preferences from the cache of PreferenceManager2, which may not have + // the value just set yet. + PreferenceManager2.getInstance(context).withFreshCache { idp.onPreferencesChanged(context) } } fun recreate() {