Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 104 ยท Projects

Project: To-do with Reminders

Build a to-do app with settings in DataStore, reminders scheduled by WorkManager, notifications with permission handling and hoisted state, plus runnable Kotlin stand-ins.

A to-do app is only useful if it tells you when something is due. That small feature pulls in four topics at once: settings that must survive restarts, background work that runs when the app is closed, notifications that need a channel and a runtime permission, and UI state that is shared cleanly between a list and a settings screen.

In this project you will design those pieces and see how they fit. The tasks themselves would be stored in Room, exactly as in the Notes app, so here we focus on what is new. The real code (DataStore, WorkManager, notifications, Compose) is read-only: the site has no emulator and cannot wake an app in the background. The TryIts are plain Kotlin stand-ins on Piston. One models the filtering and state hoisting, the other is a small fake scheduler with a fake clock that behaves like WorkManager's unique work. You will find it useful to have DataStore, WorkManager, services and notifications and state hoisting open nearby.

What we are building

  • A list of tasks, each with a title, an optional due time and a done flag.
  • Two settings: show completed tasks and sort order (by due time or by title). They are saved with DataStore and apply to the list immediately.
  • A reminder for each task with a due time, shown as a notification ten minutes before. Completing a task cancels its reminder. Editing the due time replaces it.
  • A clear message when notifications are not allowed, instead of silent failure.
flowchart LR
    UI["Compose list and settings"] --> VM["TodoViewModel"]
    VM --> Repo["TodoRepository (Room)"]
    VM --> Prefs["SettingsRepository (DataStore)"]
    VM --> Rem["ReminderScheduler"]
    Rem --> WM["WorkManager"]
    WM --> W["ReminderWorker"]
    W --> N["Notification"]

The ViewModel is the only place that knows about all three data sources. The worker runs later, outside the UI.

Step 1: settings in DataStore

Settings are small key-value pairs, which is exactly what Preferences DataStore is for. Reads are a Flow, so when the user flips a switch, every screen observing the settings updates. Writes are transactional and suspend.

Kotlin
// read-only: real DataStore code
private val Context.dataStore by preferencesDataStore(name = "settings")

enum class SortOrder { DUE_TIME, TITLE }

data class Settings(val showCompleted: Boolean = true, val sortOrder: SortOrder = SortOrder.DUE_TIME)

class SettingsRepository(private val store: DataStore<Preferences>) {
    private object Keys {
        val SHOW_COMPLETED = booleanPreferencesKey("show_completed")
        val SORT_ORDER = stringPreferencesKey("sort_order")
    }

    val settings: Flow<Settings> = store.data.map { prefs ->
        Settings(
            showCompleted = prefs[Keys.SHOW_COMPLETED] ?: true,
            sortOrder = prefs[Keys.SORT_ORDER]?.let { runCatching { SortOrder.valueOf(it) }.getOrNull() }
                ?: SortOrder.DUE_TIME,
        )
    }

    suspend fun update(change: (Settings) -> Settings) {
        store.edit { prefs ->
            val next = change(settings.first())
            prefs[Keys.SHOW_COMPLETED] = next.showCompleted
            prefs[Keys.SORT_ORDER] = next.sortOrder.name
        }
    }
}

Two details matter. The enum is stored by name and read back defensively: if you rename an enum value in a later release, an old stored string must not crash the app, so unknown values fall back to the default. And the defaults live in one place, the Settings data class, so a fresh install and a missing key behave the same.

Step 2: the list, the filters and hoisted state

The visible list is a pure function of three things: the tasks, the settings and the current time. Writing it as a plain function makes it trivial to test. The screen itself is split into a stateful part (it owns the state and handles events) and a stateless part that only draws what it is given. That is state hoisting in practice.

Kotlin
// read-only: stateless screen and its stateful wrapper
@Composable
fun TodoRoute(vm: TodoViewModel = hiltViewModel()) {
    val state by vm.uiState.collectAsStateWithLifecycle()
    TodoScreen(
        state = state,
        onToggle = vm::onToggle,
        onShowCompleted = vm::onShowCompleted,
        onSortOrder = vm::onSortOrder,
    )
}

@Composable
fun TodoScreen(
    state: TodoUiState,
    onToggle: (Int) -> Unit,
    onShowCompleted: (Boolean) -> Unit,
    onSortOrder: (SortOrder) -> Unit,
) { /* only draws state, never stores it */ }

Because TodoScreen takes plain values and callbacks, a @Preview can show an empty state, an overdue state and a long list without any ViewModel, database or DataStore.

The first TryIt runs the logic behind it. SettingsStore plays DataStore (it notifies observers when a value changes), visibleTodos is the pure filter-and-sort function, renderScreen is a stateless "composable" that returns text, and TodoScreenHolder is the stateful wrapper. Times are minutes since midnight to keep the numbers readable.

Kotlin Todo list: settings, filters and hoisted state (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Check the output: with the default settings, tasks are ordered by due time with the undated "buy flowers" after the dated ones and the finished task at the very bottom. "Pay rent" is overdue (08:00 is before 09:00) until it is ticked off. After hiding completed tasks, both finished tasks disappear. Sorting by title lowercases first, so "buy flowers" lands between "Call dentist" and "Gym" the way a person would expect, instead of after every capital letter.

Step 3: scheduling reminders with WorkManager

When the app is closed, something else has to wake up at the right time. WorkManager is the right tool for deferrable work that must still happen: it survives process death and device restarts and respects battery rules. Each reminder is a OneTimeWorkRequest with an initial delay. We give each one a unique name based on the task id, so that rescheduling replaces the old request instead of creating a duplicate.

Kotlin
// read-only: real WorkManager code
class ReminderScheduler(private val workManager: WorkManager) {

    fun schedule(todoId: Int, title: String, dueAtMillis: Long, nowMillis: Long) {
        val remindAt = dueAtMillis - 10 * 60_000L
        val delay = (remindAt - nowMillis).coerceAtLeast(0)

        val request = OneTimeWorkRequestBuilder<ReminderWorker>()
            .setInitialDelay(delay, TimeUnit.MILLISECONDS)
            .setInputData(workDataOf("id" to todoId, "title" to title))
            .build()

        workManager.enqueueUniqueWork("reminder-$todoId", ExistingWorkPolicy.REPLACE, request)
    }

    fun cancel(todoId: Int) {
        workManager.cancelUniqueWork("reminder-$todoId")
    }
}

class ReminderWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        val id = inputData.getInt("id", -1)
        val title = inputData.getString("title") ?: return Result.failure()
        if (id == -1) return Result.failure()
        NotificationHelper.showReminder(applicationContext, id, title)
        return Result.success()
    }
}

An honest limit: WorkManager timing is approximate. With Doze and battery optimizations, a reminder might arrive a few minutes late. For a to-do list that is acceptable. If exact timing is part of the product (an alarm clock or a medication app), you need AlarmManager with exact alarms, which Android restricts and which requires the user's consent on recent versions. Choose deliberately, and say so in your app's description. See Services, Notifications and Foreground Work for the comparison.

Also remember to cancel the work when its reason disappears: when the task is completed, deleted, or its due time is cleared.

Step 4: notifications and the permission

A notification needs a channel (created once, usually when the app starts) and, on Android 13 and later, the runtime permission POST_NOTIFICATIONS. If the permission is denied, notify silently does nothing, so check first and give the user a way to understand why they get no reminders.

Kotlin
// read-only: channel and notification
object NotificationHelper {
    const val CHANNEL_ID = "reminders"

    fun createChannel(context: Context) {
        val channel = NotificationChannel(CHANNEL_ID, "Reminders", NotificationManager.IMPORTANCE_DEFAULT)
        context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
    }

    fun showReminder(context: Context, id: Int, title: String) {
        val granted = Build.VERSION.SDK_INT < 33 ||
            ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
                PackageManager.PERMISSION_GRANTED
        if (!granted) return

        val notification = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_reminder)
            .setContentTitle("Due soon")
            .setContentText(title)
            .setAutoCancel(true)
            .build()
        NotificationManagerCompat.from(context).notify(id, notification)
    }
}

Ask for the permission at a meaningful moment, for example when the user first sets a due time, with a short explanation, not at app launch. The permissions lesson shows the request contract and what to do after a denial. Use the task id as the notification id so a second reminder for the same task updates the existing notification instead of stacking.

Step 5: a runnable scheduler

The second TryIt is a miniature of the whole mechanism. FakeWorkManager holds requests with a run time and a unique name. Time only moves when we call advanceTo, so everything is deterministic. FakeNotifier has a permission flag. A ReminderScheduler with the same shape as the real one connects them to the to-do logic.

Kotlin Reminder scheduler with unique work and permission (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Walk through the output. After the three schedule calls there are three pending requests. Rescheduling the meeting changed its entry instead of adding a second one, because the unique name reminder-1 plus REPLACE removed the old request. Completing "Submit report" removed its request completely. At 09:30 the dentist reminder fired (due 09:30, lead time 10 minutes, so it was ready at 09:20). Later the meeting reminder at 10:50 was dropped because permission was denied. That mirrors the real behavior, and it is why the UI should surface the permission state instead of pretending reminders work.

The last scenario shows a boundary case in the real code too: a due time less than ten minutes away would give a negative delay, which coerceAtLeast(0) turns into "run as soon as possible".

Putting it together in the ViewModel

The ViewModel combines the Room task list with the settings flow and exposes one state. Every task change also keeps the scheduler in sync, so the reminder rules live in one place.

Kotlin
// read-only: the ViewModel's rules
val uiState: StateFlow<TodoUiState> =
    combine(todoRepo.todos, settingsRepo.settings) { todos, settings ->
        TodoUiState(visibleTodos(todos, settings, nowMinute()), settings)
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), TodoUiState())

fun onToggle(todo: Todo) = viewModelScope.launch {
    todoRepo.setDone(todo.id, !todo.done)
    if (!todo.done) scheduler.cancel(todo.id)                 // just completed
    else todo.dueAt?.let { scheduler.schedule(todo.id, todo.title, it, System.currentTimeMillis()) }
}

One more design rule: Room remains the source of truth for tasks. The scheduler is derived state, so if it ever gets out of sync (for example after restoring a backup), you can rebuild it by scheduling a reminder for every open task with a future due time. A good place to do that is a small worker that runs once at app start.

Ideas for extending it

  • A repeat option (daily, weekly) that schedules the next reminder when the current one fires.
  • A snooze action button on the notification, handled by a PendingIntent that enqueues a new request.
  • A daily summary with PeriodicWorkRequest (minimum interval 15 minutes, so use it for coarse tasks only).
  • Tests: visibleTodos is a pure function and the scheduler can be tested with WorkManager's testing helpers (testing ViewModels).

Common mistakes

  • Scheduling without a unique name, so every edit creates another reminder.
  • Forgetting to cancel work for completed or deleted tasks, which leads to ghost notifications.
  • Creating the notification without a channel (nothing is shown on Android 8 and later) or ignoring the Android 13 permission.
  • Promising exact reminder times while using WorkManager.
  • Storing the enum's ordinal in DataStore instead of its name, which breaks when the order changes.
  • Putting the filter logic inside the composable, where it cannot be tested or previewed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does each reminder use a unique work name like reminder-<id> with REPLACE?

    A unique name identifies the task's reminder. REPLACE removes the previous request with that name, so each task has at most one pending reminder.
  2. 2. What happens when notifications are posted without the POST_NOTIFICATIONS permission on Android 13+?

    The call silently has no effect. Check the permission and explain to the user, ideally with a way to open the settings.
  3. 3. Why is TodoScreen written to take state and callbacks instead of a ViewModel?

    A stateless composable only draws its input. Previews and tests can feed it any state without a database, DataStore or ViewModel.
  4. 4. When is WorkManager NOT the right choice for a reminder?

    WorkManager timing is approximate because of Doze and battery policies. Exact alarms need AlarmManager and extra user consent.
  5. 5. Why store the sort order in DataStore by enum name and fall back to a default for unknown values?

    Stored data outlives app versions. Reading defensively means an old value never crashes the app; it just resets to the default.

Summary

  • Settings live in Preferences DataStore, exposed as a Flow with defaults kept in one data class and enums stored by name.
  • The visible list is a pure function of tasks, settings and time, which makes it easy to test; the screen is split into a stateless part and a stateful wrapper.
  • Reminders are unique OneTimeWorkRequests with an initial delay, replaced on edit and cancelled when the task is done; timing is approximate.
  • Notifications need a channel and, on Android 13 and later, the runtime permission; handle denial visibly.
  • Room stays the source of truth, and the scheduler is derived state that can always be rebuilt.
  • The DataStore, WorkManager and notification code is read-only; the TryIts are Kotlin stand-ins with fake time and a fake notifier.

Next: Project: Weather App