DEV Community

ReClaim
ReClaim

Posted on AI-assisted

Habit streaks on an Android Home screen: one row per day, derived streaks, and the edit that rewrites history

We're building ReClaim, a minimalist Android launcher that's on Google Play. One of the newest things we've built for its Home screen (not in the Play build yet) is a habit mark: a small round button with an icon. You tap it when you've done the thing, like a walk or some reading, and a ring fills in. Up to four habits can sit on Home. Each one has a schedule and a target, plus a streak you see when you open it.

A habit tracker sounds like a weekend project. The storage really was tiny. Everything else took longer: what counts as a "day", when a streak breaks, what "three times a week" means, and how a tap feels instant when the write hasn't landed yet. This post walks through our code for each of those, and one design choice that has a cost I didn't see at first: every streak is recomputed from raw taps, so editing a habit rewrites its past.

Stack: Kotlin, Jetpack Compose, Hilt, Room, coroutines, minSdk 26, targetSdk 36. All code below is copied from the repo.

One row per habit per day

There's no streak column and no "done" flag anywhere. The database stores the habit's rules and a count of taps per day:

/**
 * A named habit the home icon can mark, such as a walk or reading.
 * [dayMask] matches schedules: bit 0 is Monday through bit 6 Sunday.
 * [timesPerDay] is how many taps count the day. One is the usual habit.
 * [weekTarget] is 0 when those days apply. 1 through 7 means that many days in a Monday week, on any days.
 */
@Entity(tableName = "habits")
data class HabitEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val name: String,
    val dayMask: Int,
    val timesPerDay: Int,
    val position: Int,
    val createdAt: Long,
    /** [com.reclaim.launcher.data.habit.HabitLogo] name. Existing rows are Check. */
    @ColumnInfo(defaultValue = "'CHECK'")
    val logo: String = "CHECK",
    /** 0 uses [dayMask]. 1..7 is how many days count in the Monday–Sunday week. */
    @ColumnInfo(defaultValue = "0")
    val weekTarget: Int = 0,
)

/** How many times [habitId] was marked on the local epoch day [epochDay]. One row per day. */
@Entity(tableName = "habit_logs")
data class HabitLogEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val habitId: Long,
    val epochDay: Long,
    val count: Int,
)
Enter fullscreen mode Exit fullscreen mode

The day is a local epoch day, the same choice our to-do list made. The LocalDate docs describe it as "a simple incrementing count of days where day 0 is 1970-01-01 (ISO)." A tap at 11:58 PM belongs to the day you were living, not to a UTC instant that might fall on tomorrow. And every calendar step below is plusDays or minusDays on a LocalDate, never a multiple of 86,400,000 milliseconds, so daylight saving changes can't make a day 23 or 25 hours long.

The same bit layout as our scheduled blocks drives which days a habit is "on":

fun Habit.scheduledOn(date: LocalDate): Boolean =
    dayMask and (1 shl (date.dayOfWeek.value - 1)) != 0
Enter fullscreen mode Exit fullscreen mode

That works because DayOfWeek.getValue() is numbered "following the ISO-8601 standard, from 1 (Monday) to 7 (Sunday)." Monday is bit 0.

Counting a tap

All writes go through one repository with a Mutex:

    suspend fun logOne(habitId: Long, day: Long = LocalDate.now().toEpochDay()): Int? = mutex.withLock {
        val habit = dao.find(habitId) ?: return null
        val target = habit.timesPerDay.coerceIn(1, 8)
        val row = dao.findLog(habitId, day)
        val current = row?.count ?: 0
        if (current >= target) return current
        val next = current + 1
        if (row == null) {
            dao.insertLog(HabitLogEntity(habitId = habitId, epochDay = day, count = next))
        } else {
            dao.updateLog(row.copy(count = next))
        }
        next
    }
Enter fullscreen mode Exit fullscreen mode

Two details matter. The count stops at the day's target. Once you've hit it, another tap opens the habit's detail sheet instead of counting past it. And null means the habit is gone, which the caller uses to drop its optimistic state (more on that below).

The thing I'd change: "one row per day" is a promise only that Mutex keeps. The table has no unique index on (habitId, epochDay). The repository is a Hilt singleton and the only writer during normal use, so in practice it holds. But the database itself wouldn't stop a second row, and the readers pick one row per day instead of adding them up. Room's docs cover exactly this: "To enforce this uniqueness, set the unique property of an @Index annotation to true." Adding that index takes a migration, and that's on the list.

Deriving the streak

The whole stats screen comes from one pure function, habitStats(habit, logs, today, todayCount). Its comment states the rules:

A scheduled day counts once its taps reach [Habit.timesPerDay]. Today does not break the streak until the day is over. Days that are not on the schedule are skipped.

Here's the current streak for a fixed-days habit:

private fun currentStreak(habit: Habit, byDay: Map<Long, Int>, today: LocalDate, target: Int): Int {
    var date = today
    val todayMet = (byDay[today.toEpochDay()] ?: 0) >= target
    if (!habit.scheduledOn(date) || !todayMet) date = date.minusDays(1)
    var streak = 0
    repeat(4_000) {
        if (habit.scheduledOn(date)) {
            if ((byDay[date.toEpochDay()] ?: 0) >= target) streak++ else return streak
        }
        date = date.minusDays(1)
    }
    return streak
}
Enter fullscreen mode Exit fullscreen mode

The line that starts the walk on yesterday when today isn't done yet is the whole "today doesn't count against you" rule. Without it, everyone's streak would read zero every morning until their first tap. Unscheduled days are walked past without counting or breaking. The repeat(4_000) is a bound, not a feature: about eleven years of days. The loop needs some limit, and no streak will hit that one.

Best streak goes the other way. It walks forward from the earliest log to today, keeps a running count, and resets it on a missed scheduled day, except for today when today isn't done yet. If you tap on a day that's off the schedule, the tap is saved and shows as "1 marked. Not scheduled today." A day like that can count toward the "days marked" total, but never toward either streak.

"Three days a week, any days"

Fixed days don't fit every habit. "Gym three times a week" doesn't care whether it's Monday or Thursday. So a habit can switch to a weekly target, and then the streak counts weeks:

private fun currentWeekStreak(
    byDay: Map<Long, Int>,
    today: LocalDate,
    target: Int,
    weekTarget: Int,
): Int {
    var start = mondayOf(today)
    if (daysMetInWeek(byDay, start, target) < weekTarget) start = start.minusWeeks(1)
    var streak = 0
    repeat(800) {
        if (daysMetInWeek(byDay, start, target) >= weekTarget) streak++ else return streak
        start = start.minusWeeks(1)
    }
    return streak
}
Enter fullscreen mode Exit fullscreen mode

It's the same shape one level up. The open week gets the same grace today gets: if this week hasn't reached its target yet, the walk starts from last week, so nothing breaks until Sunday is over. In this mode the day mask is ignored. For a once-a-day habit, the Home mark's ring fills by days this week rather than taps today, and once the week is full the mark dims and its accessibility label says it's "done for the week".

The week is hard-coded to start on Monday. The WeekFields docs are blunt that this is a regional choice: "The first day-of-week varies by culture. For example, the US uses Sunday, while France and the ISO-8601 standard use Monday." Someone in the US who thinks of the week as Sunday to Saturday will see their week roll over a day later than they expect. Using WeekFields.of(locale) would fix the boundary, but it would also shift which taps fall into which week for existing users. So it's a deliberate change for later, not a quick swap.

A tap can't wait for the database

On Home, the ring has to move the moment your finger lifts. The logOne write is fast, but Room only reports it on its next Flow emission, a beat later. So the ViewModel records an optimistic count first and lets the database catch up:

        val now = System.currentTimeMillis()
        if (count >= habit.timesPerDay) {
            if (now - (lastHabitLogAt[habit.id] ?: 0L) < 500L) return WidgetTap.Ignored
            return WidgetTap.ShowHabit
        }
        lastHabitLogAt[habit.id] = now
        pendingHabits.value = pendingHabits.value + (habit.id to PendingHabit(habit.id, day, count + 1))
        habitWrites[habit.id] = (habitWrites[habit.id] ?: 0) + 1
        launch {
            var saved: Int? = null
            try {
                saved = habitRepository.logOne(habit.id, day)
            } finally {
                val left = (habitWrites[habit.id] ?: 1) - 1
                if (left <= 0) habitWrites.remove(habit.id) else habitWrites[habit.id] = left
                val pending = pendingHabits.value[habit.id]
                val written = saved
                if (left <= 0 && pending != null && pending.day == day && (written == null || written >= pending.count)) {
                    pendingHabits.value = pendingHabits.value - habit.id
                }
            }
        }
Enter fullscreen mode Exit fullscreen mode

The UI state merges the two sources with a max:

        val counts = habits.habits.associate { habit ->
            val saved = habitCount(habits.logs, habit.id, habits.day)
            val pendingCount = habits.pending[habit.id]?.takeIf { it.day == habits.day }?.count ?: 0
            habit.id to maxOf(saved, pendingCount)
        }
Enter fullscreen mode Exit fullscreen mode

That sits inside a combine, which kotlinx documents as "combining the most recently emitted values by each flow". So the screen redraws when either the database or the pending map changes, whichever comes first.

A few things here took more than one try:

  • Writes in flight are counted, not flagged. Three quick taps on a three-times-a-day habit start three writes. The pending entry is only cleared when the last one finishes and the count it saved has reached the optimistic one, so the ring can't drop back mid-burst.
  • max only ever raises a count. Anything that lowers one has to clear the pending entry too. Undo does that directly. A collector on the logs Flow drops pending entries that no longer match the database once no write is in flight.
  • The 500 ms guard. The tap that completes a habit is often followed by a stray second tap. Without the guard, that second tap would open the detail sheet right after a mark. Inside half a second of the last counted tap, it's ignored.
  • The tap re-reads the date first. onHabitTap calls noteToday() before anything else, so a tap just after midnight lands on the new day even if the screen hasn't caught up yet.

That last point covers for a weaker spot. The display rolls over at midnight through a LaunchedEffect loop that delays until the zone's next start of day. It gets the length of the day right, but it's the same delay-based wait our tasks post flagged as probably not counting deep sleep. So the ring might still show yesterday as full for a while after the phone wakes. We haven't confirmed that on a device. The fix is the same as there: refresh on resume and on the system's date-change broadcast.

The practice timer can mark a habit too

Home also has a practice timer (the one that borrows Do Not Disturb). A practice can be linked to a habit, and a completed session marks it:

    private suspend fun markLinkedHabit(session: PracticeSessionEntity, endedAt: Long) {
        val practice = dao.find(session.practiceId) ?: return
        val habitId = practice.habitId ?: return
        if (!practiceCompleted(session.startedAt, endedAt, session.plannedMillis)) return
        val day = Instant.ofEpochMilli(session.startedAt).atZone(ZoneId.systemDefault()).toLocalDate().toEpochDay()
        habits.logOne(habitId, day)
    }
Enter fullscreen mode Exit fullscreen mode

The mark goes on the day the session started. That's the day the practice's own totals use, so a 30-minute session that begins at 11:50 PM counts for the evening you were in. Because it goes through the same logOne, it can't push a day past its target, and it can't race a tap into two rows.

The cost of deriving everything: edits rewrite the past

Here's the design choice I mentioned at the top. Because streaks are recomputed from raw counts using the habit's current rules, changing the rules changes history. Raise "times a day" from 1 to 2, and every past day with one tap stops counting, so your streak goes to zero. Drop Wednesdays from the schedule, and old missed Wednesdays stop breaking anything. Switch to a weekly target, and the whole history gets re-read as weeks.

The editor at least doesn't hide it. It runs habitStats on the edited copy, so the streak on screen changes as you adjust the schedule. But there's no warning before you save. The taps themselves are never touched, so changing the setting back restores the old streak, but you'd have to know to do that. The helper text in the editor says "A missed day ends the streak. Today still counts until the day is over." It says nothing about edits.

There are a few fixes. One is to store the target on each log row when it's written. Another is to keep schedule versions with an effective-from day. A third is to stay derived and warn before saving. I haven't picked one. Deriving is still why the rest of the code is this small: no streak to keep in sync, nothing to repair after a backup restore, and the same function serves Home, the sheet and the editor.

Other open items

  • No backfill. You can only mark or undo today. If you did the walk yesterday and forgot to tap, the streak is broken and there's no fix. That keeps the record honest, but it will annoy someone.
  • No tests on the stats. habitStats is pure and takes today as a parameter, so it's the easiest code in the app to unit test. Right now nothing tests it.
  • Recomputed on every draw. Each Home mark calls habitStats during composition, and best streak walks every day since the first log. At four habits and a few years of rows that's small, but it isn't memoized and we haven't measured it.
  • Not in the Play build yet. Habits are new code. The Play listing's last update predates them, so treat this as work in progress. When it ships, habits will be part of the local backup and the optional account backup, like tasks.

Takeaways

  • Store the smallest fact, a count per local day, and derive streaks from it. Then decide up front what an edit should do to the past.
  • Give "today" grace in the streak walk, or every streak reads zero each morning.
  • If a table has a "one row per X" rule, put it in a unique index, not just a lock.
  • For instant taps, keep an optimistic layer that can only raise values, count the writes in flight, and clear it when the database agrees.
  • A week has a start day, and it isn't the same everywhere.

ReClaim is free on Google Play. Habits are the "build" side of the app. Most of the rest is about breaking the checking habit, which our post on how to stop opening apps on autopilot covers from the user's side.

This post was drafted with AI assistance and reviewed by the ReClaim team.

Top comments (0)