Skip to content

Introduce FetchTask to tie database observation to view lifetime#295

Merged
stephencelis merged 10 commits into
mainfrom
fetch-task
Nov 26, 2025
Merged

Introduce FetchTask to tie database observation to view lifetime#295
stephencelis merged 10 commits into
mainfrom
fetch-task

Conversation

@stephencelis
Copy link
Copy Markdown
Member

@stephencelis stephencelis commented Nov 14, 2025

Currently, the @FetchAll, @FetchOne, and @Fetch property wrappers work the same way that SwiftData's @Query property wrapper work: they observe and cause view updates as long as they are in the view hierarchy, regardless of if the view is visible or not. That means a list view powered by a @FetchAll will continue to recompute even if you're drilled down into a detail screen.

To work around this, you must explicitly stop observation, using events like onDisappear:

.task {
  try? await $reminders.load(Reminder.order(by: \.isCompleted))
}
.onDisappear {
  Task { try await $reminders.load(Reminder.none) }
}

This PR introduces a new FetchTask type that is returned from load, which you can optionally await to tie the cancellation of the current Swift task to the database observation. To migrate to it from the above workaround:

 .task {
-  try? await $reminders.load(Reminder.order(by: \.isCompleted))
+  try? await $reminders.load(Reminder.order(by: \.isCompleted)).task
 }
-.onDisappear {
-  Task { try await $reminders.load(Reminder.none) }
-}

Comment thread Sources/SQLiteData/FetchSubscription.swift
Comment thread Sources/SQLiteData/FetchTask.swift Outdated
@stephencelis stephencelis merged commit 0aba45e into main Nov 26, 2025
5 checks passed
@stephencelis stephencelis deleted the fetch-task branch November 26, 2025 14:51
bok- pushed a commit to bok-/sqlite-data-with-traits that referenced this pull request Dec 15, 2025
…ointfreeco#295)

* Support tasks for loading query.

* wip

* wip

* new test

* wip

* wip

* wip

* Add @discardableResult to load functions

* Added a migration guide.

---------

Co-authored-by: Brandon Williams <mbrandonw@hey.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants