DEV Community

ReClaim
ReClaim

Posted on AI-assisted

Tasks on an Android Home screen: store the day, not the instant, and don't trust delay() to find midnight

We're building ReClaim, a minimalist Android launcher that's on Google Play. Under the clock on its Home screen sits a short to-do list: three open tasks by default, a "2 more" line if there are others, and a tap target to add one. It's the only thing on Home that you type into yourself, so we wanted it to feel like a sticky note and not like a project manager.

A to-do list sounds like the easiest feature in the app. It's a Room table with a title and a checkbox. Most of the work turned out to be about one question: what day is it? Due dates, "Today" and "Tomorrow" labels, a "due soon" filter and an auto-clear for finished tasks all depend on the answer. On a launcher, the answer has to stay right on a screen that may sit open for days.

Stack: Kotlin, Jetpack Compose, Hilt, Room 2.6, DataStore, kotlinx.coroutines 1.9, minSdk 26. Snippets are trimmed from the real code; // ... marks cuts. The last post covered how the same task list stays readable over the wallpaper. This one is about the data and the dates.

1. Store the day, not the instant

A due date in ReClaim is a calendar day. It's not a timestamp. The entity stores it as an epoch day:

/**
 * A to-do shown on the Home screen. [dueEpochDay] is a calendar day ([java.time.LocalDate.toEpochDay]),
 * not an instant — tasks are due "on Friday", never "at 14:32 UTC", and a day survives timezone
 * changes without shifting. [completedAt] (epoch millis) doubles as the done flag: null = open.
 */
@Entity(tableName = "tasks")
data class TaskEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val dueEpochDay: Long? = null,
    val completedAt: Long? = null,
    val createdAt: Long,
    val categoryId: Long? = null,
)
Enter fullscreen mode Exit fullscreen mode

The Java docs define the epoch day as "a simple incrementing count of days where day 0 is 1970-01-01 (ISO)". There's no zone in it. If you store "Friday" as midnight in the zone you were in when you typed it, then fly three time zones west, the task becomes due on Thursday evening. An epoch day can't do that. It means "Friday" wherever the phone is.

There are two other choices in that entity. completedAt is both the done flag and the completion time, so there's no boolean that can disagree with a timestamp. And createdAt is kept for ordering, not for display, which matters in the next section.

The UI model turns the number back into a LocalDate on read, so no screen ever does day math on raw longs:

data class Task(/* ... */ val dueEpochDay: Long?, val completedAt: Long?, /* ... */) {
    val isCompleted: Boolean get() = completedAt != null
    val dueDate: LocalDate? get() = dueEpochDay?.let(LocalDate::ofEpochDay)
}
Enter fullscreen mode Exit fullscreen mode

2. One sort order that never reshuffles

The repository exposes open tasks in a single order, and every screen uses it:

/**
 * Open tasks, soonest due first. Undated tasks come after every dated one — a date is a
 * commitment the user made, so it always outranks "someday" — and ties fall back to creation
 * order so the list never reshuffles on its own.
 */
val openTasks: Flow<List<Task>> = all.map { list ->
    list.filter { !it.isCompleted }
        .sortedWith(compareBy<Task, Long?>(nullsLast()) { it.dueEpochDay }.thenBy { it.createdAt })
}
Enter fullscreen mode Exit fullscreen mode

Kotlin's nullsLast() is documented as "considering null value greater than any other value", which is exactly "someday goes to the bottom". The createdAt tie-break is the part that matters on Home. Without it, tasks with the same due day (or no day) keep whatever order the query returned. Our SELECT * FROM tasks has no ORDER BY, and SQLite's docs say that without one "the order in which the rows are returned is undefined". A list that changes order after you tick and untick a task feels broken, even if nothing else is wrong. With createdAt as the tie-break, untick a task and it goes back exactly where it was.

Completed tasks get their own flow, newest first by completedAt.

3. The Home slice: filter, take, count the rest

Home doesn't show the whole list. Settings decide how many tasks appear (three by default), whether to show only tasks that are due soon, and whether to pin one category. That's one combine in the ViewModel:

val homeTasks: StateFlow<HomeTasks> = combine(
    taskRepository.openTasks,
    settingsRepository.settings,
) { tasks, settings ->
    val today = LocalDate.now().toEpochDay()
    val matching = tasks.filter { task ->
        val categoryOk = settings.tasksHomeCategoryId == null || task.categoryId == settings.tasksHomeCategoryId
        val dueOk = when (settings.tasksHomeFilter) {
            TaskHomeFilter.ALL -> true
            // "Due soon" is today and anything already overdue — the things Home should nag about.
            TaskHomeFilter.DUE_SOON -> task.dueEpochDay != null && task.dueEpochDay <= today
        }
        categoryOk && dueOk
    }
    val visible = matching.take(settings.tasksHomeCount)
    HomeTasks(visible, matching.size - visible.size)
}.stateInDefault(HomeTasks())

// ...
private fun <T> Flow<T>.stateInDefault(initial: T): StateFlow<T> =
    stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial)
Enter fullscreen mode Exit fullscreen mode

Because the dates are epoch days, "due soon" is a single integer comparison: due on or before today. Overdue tasks are included on purpose. A task you missed yesterday is the one Home should keep showing you.

Look at where today comes from, though. LocalDate.now() runs inside the combine lambda, which only runs when the task list or the settings emit. Nothing in that flow ticks at midnight. If Home stays on screen from 11 PM to 1 AM, the "due soon" slice still uses yesterday's date, and tasks due today don't appear until something else changes.

In practice the window is narrower than that sounds. Home collects this flow with collectAsStateWithLifecycle, which the Android docs say begins "when the lifecycle is STARTED and stops when the lifecycle is STOPPED". WhileSubscribed(5_000) then stops the upstream five seconds after the last collector leaves. When Home comes back, the combine restarts and reads a fresh date. So the stale slice only survives while Home stays visible across midnight. It's still a bug. The fix is to make "today" an input to the combine, not something the lambda looks up.

4. A "today" that rolls over at midnight

The labels on each row ("Today", "Tomorrow", "Yesterday", a weekday, or a date) have the same problem. We did think about this one. The task list keeps "today" as Compose state and wakes itself up at the next midnight:

/**
 * Today's date as state, rolling over at midnight — so "Today" / "Tomorrow" labels on a Home screen
 * that's been sitting there for hours don't quietly go stale.
 */
@Composable
private fun rememberToday(): LocalDate {
    var today by remember { mutableStateOf(LocalDate.now()) }
    LaunchedEffect(Unit) {
        while (true) {
            val now = LocalDateTime.now()
            val nextMidnight = now.toLocalDate().plusDays(1).atStartOfDay()
            delay(Duration.between(now, nextMidnight).toMillis().coerceAtLeast(1_000L))
            today = LocalDate.now()
        }
    }
    return today
}
Enter fullscreen mode Exit fullscreen mode

The Home list and the full sheet both use it, so the row labels and the sheet's section headers (Overdue, Today, Upcoming, No date) recompose when it changes. Overdue labels also switch to the theme's error color.

When we checked this code for the post, we found two problems. Neither has been confirmed on a device yet.

delay probably doesn't count deep sleep. Compose's AndroidUiDispatcher doesn't implement kotlinx's Delay interface (we checked the current AndroidX source), so delay falls back to the coroutines library's default executor. That executor parks a thread against System.nanoTime(). Android's SystemClock docs list System.nanoTime() among the timers based on uptimeMillis(), and say that clock "stops when the system enters deep sleep (CPU off, display dark, device waiting for external input)". They describe the uptime clock as "suitable for interval timing when the interval does not span device sleep". A wait until midnight nearly always spans device sleep. If the phone goes to sleep at 11 PM, the one hour left on the timer only counts down while the CPU is awake. The labels could say "Tomorrow" for part of the next morning. Our Home clock ticks the same way, but it re-arms every minute, so its worst case is about a minute.

LocalDateTime ignores daylight saving. Duration.between on two LocalDateTimes measures wall-clock time. The day clocks spring forward is 23 hours long, but the wait is computed as 24, so that night's rollover fires around 1 AM. (When clocks fall back, it fires an hour early, finds the date hasn't changed, and simply waits again.)

The fix we're planning doesn't trust a timer at all. Re-read the date whenever Home starts or resumes. While the screen is on, listen for the system's date and time broadcasts: Intent.ACTION_DATE_CHANGED ("The date has changed"), plus time-zone changes. The SystemClock docs say the same for wall-clock code: "consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes." And that same today should feed the combine from section 3, so the labels and the "due soon" slice can't disagree.

5. The date picker speaks UTC, and that's convenient

Adding a task is one line of typing. The title field takes focus right away, the keyboard's Done key saves, and the due date is a chip: No date, Today, Tomorrow, or Pick a date. The custom date uses Material 3's DatePicker, whose docs describe selectedDateMillis as "the selected date start of the day in UTC milliseconds from the epoch".

Usually that UTC detail causes off-by-one bugs: you convert it with the local zone, and everyone west of Greenwich gets the day before. With epoch days it works in our favor. UTC midnight of epoch day n is exactly n × 86,400,000 ms, so the conversion is a multiply in one direction and a floor division in the other:

private const val DAY_MILLIS = 86_400_000L

// DatePicker works in UTC-midnight millis, so an epoch day converts by a plain multiply.
val pickerState = rememberDatePickerState(initialSelectedDateMillis = (dueEpochDay ?: todayDay) * DAY_MILLIS)
// ...
pickerState.selectedDateMillis?.let { dueEpochDay = Math.floorDiv(it, DAY_MILLIS) }
Enter fullscreen mode Exit fullscreen mode

No ZoneId appears anywhere in the round trip, so there's no zone to get wrong. floorDiv and not / keeps it correct for dates before 1970 too, where the millis are negative. Nobody's going to set a task due in 1969, but it costs nothing.

6. Categories are a filter, not a structure

Tasks can belong to a category ("Work", "Groceries"). We kept the due date as the only thing that groups the list. In the full sheet, categories show up as chips that narrow it. Deleting a category never deletes its tasks:

/** Deleting a category never deletes its tasks — they fall back to uncategorised. */
@Query("UPDATE tasks SET categoryId = NULL WHERE categoryId = :id")
suspend fun detachTasks(id: Long)
Enter fullscreen mode Exit fullscreen mode
fun deleteCategory(category: TaskCategory) = viewModelScope.launch {
    taskRepository.deleteCategory(category.id)
    // A Home filter pinned to this category would otherwise silently hide every task.
    if (settingsRepository.settings.first().tasksHomeCategoryId == category.id) {
        settingsRepository.setTasksHomeCategoryId(null)
    }
}
Enter fullscreen mode Exit fullscreen mode

That second check is the kind of thing that's easy to miss. Pin Home to "Work", delete "Work", and without the reset Home would show an empty list forever, with nothing on screen explaining why.

Two things here we'd do differently. deleteCategory runs the detach and the delete as two separate statements, outside a transaction. And the tables declare no foreign key, so the database doesn't enforce the "fall back to uncategorised" rule. A ForeignKey with onDelete = SET_NULL would make that rule part of the schema.

The other one is in the editor. When you create a category from inside the task editor, it gets selected for you. The editor doesn't know the new row's id, so it watches the category list and matches by name, ignoring case. Nothing stops two categories having the same name, though. Create "work" while "Work" exists and the editor picks the old one. addCategory already returns the new id from Room's @Upsert. The ViewModel just throws it away inside launch. Passing it back would remove the guess.

7. Cleaning up without a scheduler

Finished tasks can clear themselves after a day or a week. There's no WorkManager job for it. The ViewModel prunes when it starts:

init {
    // Lazy prune, same shape as BlockRepository.pruneExpired: nothing schedules this, it just
    // happens next time the launcher is up, which is soon enough for tidying a finished list.
    viewModelScope.launch {
        settingsRepository.settings.first().tasksAutoClear.windowMillis
            ?.let { taskRepository.pruneCompleted(it) }
    }
}
Enter fullscreen mode Exit fullscreen mode

That's a fair trade for tidying up, with one catch that's specific to launchers. Home's ViewModel is created once and lives as long as Home's back-stack entry, which for a launcher is usually the whole life of the process. "After a day" really means "the next time the process starts, or the Tasks settings screen opens (it gets its own ViewModel), once a day has passed". Nobody loses data this way. Finished tasks just stay a bit longer than the setting says. Unlike due dates, this window is plain milliseconds, not calendar days. "After a day" means 24 hours after you ticked it, not "tomorrow".

What's still open

To sum up the honest list:

  • The "due soon" slice on Home reads the date only when tasks or settings change, so it can stay a day behind if Home is on screen across midnight.
  • The midnight rollover for labels waits with delay, which probably doesn't count deep sleep, and computes the wait in wall-clock time, so it's an hour late on spring-forward nights. Neither is confirmed on a device. The fix is the same for both: refresh on resume and on the date/time broadcasts, and feed one today to everything.
  • Swipe-to-delete in the full sheet deletes straight away, with no undo.
  • Same-name categories make the editor's auto-select pick the wrong one.
  • Category deletion is two statements with no transaction and no foreign key.

None of these fixes have shipped yet.

What we'd tell another team

  • Store due dates as days. LocalDate.toEpochDay() gives you a zone-free integer that sorts, compares and filters with plain math.
  • Always add a tie-break. Sorting by due date alone lets equal items move around. Creation time keeps a list still.
  • "Today" is an input, not a lookup. If a value depends on the date, make the date a flow or state that changes, and pass it in. Don't call now() inside a lambda that only runs when something else changes.
  • Don't wait for midnight with a timer. On Android, ordinary delays run on a clock that stops in deep sleep. Re-check the date when the screen comes back, and let the system tell you when it changes.

If you'd like to see the list on a real Home screen, ReClaim is free on Google Play. For why Home only shows a few tasks and nothing else, see our guide to a minimal Android home screen.

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

Top comments (1)

Collapse
 
beusebiu profile image
Eusebiu Balan •

The screen that sits open got me too, in a much smaller way 😅

My app worked out "today" once for the week strip on its home screen. Leave it open overnight and next morning yesterday was still today, and the real today was a future day you couldn't tap.

It moves at midnight now, and again when the app comes back to the front.