Modern Apps git

← Modern-Apps.git

library: queue achievement unlocks instead of keeping only one (#ux-audit)

Commit
1bdc2954db6bcdccfd5b480d1acd5b348a9ae6d6
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:20 UTC (23 days ago)
Parents
4021205
Symptom: when two achievements unlocked close together - common on a
win, which can complete "first win" and a progress milestone in the
same move - only the last one was ever shown. The first toast was
replaced before it appeared, or mid-way through its display, and the
player never learned they had earned it.

Root cause: AchievementsManager kept a single MutableStateFlow slot
(newAchievement). Every unlock assigned to it, overwriting whatever
was still waiting, and dismissNotification() cleared it to null.

Fix: unlocks now go into a FIFO queue (ArrayDeque guarded by a lock,
since unlocks land from IO coroutines). newAchievement keeps its type
and meaning for every caller - a StateFlow<Achievement?> of the toast
to show now - but it now exposes the head of the queue.
dismissNotification() pops the head and publishes the next waiting
unlock, or null when the queue is empty. No game, the Games Hub
reporter or the toast composable needed an API change.
- GameHubReporter keeps collecting newAchievement, so each queued
  unlock is still forwarded to the hub as it reaches the head;
  progress/unlock state is also synced from DataStore independently,
  so nothing is lost if the app dies with toasts still queued.
- Idempotence is unchanged: an id already in the unlocked set is not
  queued again.

User-visible effect: simultaneous unlocks now show one after another,
in the order they landed, each for its full display time.

Verification: new AchievementsQueueTest - two unlocks show in order
(the second, once persisted, does not displace the first; dismiss
reveals it; dismiss again empties), a burst of three loses none, and
dismissing an empty queue is harmless. The existing LibraryState2Test
/ LibraryGameHubTest achievement cases still pass unchanged.
:library:testDebugUnitTest.

Diff

library/src/main/java/com/vayunmathur/library/util/AchievementsManager.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/AchievementsManager.kt b/library/src/main/java/com/vayunmathur/library/util/AchievementsManager.ktindex 90a68fbabb..d48b3411b8 100644--- a/library/src/main/java/com/vayunmathur/library/util/AchievementsManager.kt+++ b/library/src/main/java/com/vayunmathur/library/util/AchievementsManager.kt@@ -6,6 +6,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch@@ -36,17 +37,23 @@ abstract class AchievementsManager(      private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) +    /**+     * Unlocks not yet shown, oldest first. Unlocks often land together — a win can complete "first win"+     * and "ten wins" in one move — and each deserves its own toast, so they wait their turn here instead+     * of overwriting one another.+     */+    private val pending = ArrayDeque<Achievement>()     private val _newAchievement = MutableStateFlow<Achievement?>(null)-    val newAchievement = _newAchievement.asStateFlow()++    /** The unlock to show now: the oldest one not yet dismissed, or null when none is waiting. */+    val newAchievement: StateFlow<Achievement?> = _newAchievement.asStateFlow()      abstract fun checkExistingAchievements()      fun onAchievementUnlocked(id: String) {         val achievement = achievements.find { it.id == id } ?: return         scope.launch {-            if (ds.addStringToSetIfAbsent(unlockedKey, id)) {-                _newAchievement.value = achievement-            }+            if (ds.addStringToSetIfAbsent(unlockedKey, id)) enqueue(achievement)         }     } @@ -75,8 +82,19 @@ abstract class AchievementsManager(         }     } +    /** The current toast is done: drop it and move the next waiting unlock, if any, into [newAchievement]. */     fun dismissNotification() {-        _newAchievement.value = null+        synchronized(pending) {+            pending.removeFirstOrNull()+            _newAchievement.value = pending.firstOrNull()+        }+    }++    private fun enqueue(achievement: Achievement) {+        synchronized(pending) {+            pending.addLast(achievement)+            _newAchievement.value = pending.first()+        }     }      /** Forget everything stored under [keyPrefix]. Used when the save it belongs to is deleted. */
library/src/test/java/com/vayunmathur/library/util/AchievementsQueueTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/AchievementsQueueTest.kt b/library/src/test/java/com/vayunmathur/library/util/AchievementsQueueTest.ktnew file mode 100644index 0000000000..c1f2083adf--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/AchievementsQueueTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.library.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Unlocks that land together are shown one after another, oldest first, and none is dropped. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AchievementsQueueTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private class Achievements(context: Context, prefix: String) : AchievementsManager(+        context,+        """[{"id":"first_win","name":"First Win","description":"win once","targetProgress":1},+            {"id":"win_10","name":"Ten","description":"win ten","targetProgress":10},+            {"id":"win_50","name":"Fifty","description":"win fifty","targetProgress":50}]""",+        prefix,+    ) {+        override fun checkExistingAchievements() {}+    }++    private suspend fun await(cond: suspend () -> Boolean) {+        withTimeout(5_000) { while (!cond()) delay(20) }+    }++    private suspend fun Achievements.isStored(id: String) =+        getAchievementStatuses().first().first { it.achievement.id == id }.isUnlocked++    @Test fun twoQueuedUnlocksShowInOrder() = runBlocking {+        val mgr = Achievements(ctx, "queue${System.nanoTime()}_")+        mgr.onAchievementUnlocked("first_win")+        await { mgr.newAchievement.value?.id == "first_win" }+        mgr.onAchievementUnlocked("win_10")+        // Wait until the second unlock has really landed, then check it did not replace the first.+        await { mgr.isStored("win_10") }+        delay(50)+        assertEquals("first_win", mgr.newAchievement.value?.id)++        mgr.dismissNotification()+        assertEquals("win_10", mgr.newAchievement.value?.id)+        mgr.dismissNotification()+        assertNull(mgr.newAchievement.value)+    }++    @Test fun aBurstOfUnlocksLosesNone() = runBlocking {+        val mgr = Achievements(ctx, "burst${System.nanoTime()}_")+        listOf("first_win", "win_10", "win_50").forEach(mgr::onAchievementUnlocked)+        await { listOf("first_win", "win_10", "win_50").all { mgr.isStored(it) } }+        delay(50)+        val shown = mutableListOf<String>()+        while (true) {+            val current = mgr.newAchievement.value ?: break+            shown += current.id+            mgr.dismissNotification()+        }+        assertEquals(setOf("first_win", "win_10", "win_50"), shown.toSet())+        assertEquals(3, shown.size)+    }++    @Test fun dismissingWithNothingQueuedIsHarmless() {+        val mgr = Achievements(ctx, "empty${System.nanoTime()}_")+        mgr.dismissNotification()+        mgr.dismissNotification()+        assertNull(mgr.newAchievement.value)+    }+}