Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,33 @@ asynchronous code runs:
explicitly `@concurrent`, so it still runs off its caller’s actor, and existing interceptors
don’t need to change.

This release also adds support for live queries whose results change after they’re produced, like
a search over a local database that should update when the database does:

- The new `LiveQueryResultUpdatesProducer` protocol returns an `AsyncSequence` of results for each
query fragment. Create a live query that uses one with `LiveQuery.init(resultUpdatesProducer:)`.
Each value the sequence produces replaces the live query’s results, and when the query fragment
changes, the live query cancels its iteration of the previous fragment’s sequence.
- `LiveQueryResultsProducer` now refines `LiveQueryResultUpdatesProducer`, with a default
implementation of `resultUpdates(forQueryFragment:)` that produces results once. Existing
conformances don’t need to change.
- `LiveQuery` now cancels result production for a query fragment when a newer fragment arrives,
and discards any results it produces later. Previously, a live query waited for each
fragment’s results before producing the next fragment’s. That delayed results for the latest
fragment by however long the previous call had left, and it showed results for a fragment the
user had already moved past. Now, result production for the latest fragment starts right away,
and results that arrive for a fragment the user has moved past are discarded. This change is
required to support result updates sequences, because otherwise a live query would wait for
the first fragment’s sequence to finish; if it never did, the live query would never produce
results for later fragments.

You may notice the change if your results producer is slow relative to its debounce duration.
While someone types in short bursts, each burst cancels the previous call, so intermediate
results appear less often. Choosing a debounce duration close to your producer’s typical
latency avoids this. If your producer ignores cancellation, it still runs to completion, but
its results are no longer shown. If its work must finish, for example to cache results, run
that work in a separate task that cancellation doesn’t reach.


## 1.11.0: August 4, 2026

Expand Down
1 change: 1 addition & 0 deletions Sources/DevFoundation/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ for paging through data, and essential utility types for building robust applica

- ``LiveQuery``
- ``LiveQueryResultsProducer``
- ``LiveQueryResultUpdatesProducer``
- ``LiveQuerySchedulingStrategy``

### Localizing with Remote Content
Expand Down
178 changes: 148 additions & 30 deletions Sources/DevFoundation/Live Query/LiveQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@ import Synchronization
/// ## Overview
///
/// `LiveQuery` provides a reactive interface for search-as-you-type functionality. It coordinates between user input
/// and result production, handling common concerns like debouncing, duplicate removal, and error management.
/// and result production, handling common concerns like debouncing, duplicate removal, cancellation, and error
/// management.
///
/// Live queries get results from a producer. A ``LiveQueryResultsProducer`` produces results once for each query
/// fragment, which works well for searches whose results don’t change, like network requests. A
/// ``LiveQueryResultUpdatesProducer`` produces a sequence of results for each query fragment, which works well for
/// searches over local data that should update when the data changes. In both cases, results for a query fragment are
/// only used until the query fragment changes. When it does, the live query cancels result production for the previous
/// fragment and discards any results it produces later.
///
///
/// ## Usage
Expand All @@ -38,6 +46,10 @@ import Synchronization
///
/// let liveQuery = LiveQuery(resultsProducer: SearchProducer())
///
/// If results can change after they’re produced, provide a ``LiveQueryResultUpdatesProducer`` instead:
///
/// let liveQuery = LiveQuery(resultUpdatesProducer: NoteSearchProducer(noteStore: noteStore))
///
/// Update the query fragment to trigger result production:
///
/// liveQuery.queryFragment = "search term"
Expand All @@ -56,7 +68,7 @@ import Synchronization
///
/// ## Scheduling Strategies
///
/// The results producer’s ``LiveQueryResultsProducer/schedulingStrategy`` determines when results are generated:
/// The producer’s scheduling strategy determines when results are generated:
///
/// - ``LiveQuerySchedulingStrategy/passthrough``: Produces results immediately for every change. Best for cheap
/// operations like filtering local data.
Expand All @@ -69,6 +81,10 @@ import Synchronization
/// Errors from result production are captured in ``lastError``. The query continues operating after errors,
/// preserving the last successful results until new ones are produced.
///
/// When a result updates sequence throws an error, the live query sets ``lastError`` and stops iterating that
/// sequence, keeping its last results. Changing the query fragment starts a new sequence, and its first value clears
/// ``lastError``. Errors from a sequence that was cancelled because the query fragment changed are ignored.
///
///
/// ## Thread Safety
///
Expand All @@ -78,8 +94,8 @@ import Synchronization
///
/// ## Performance
///
/// The query automatically deduplicates identical fragments and canonicalizes input through the results producer.
/// This prevents unnecessary work when users make redundant changes.
/// The query automatically deduplicates identical fragments and canonicalizes input through the producer. This
/// prevents unnecessary work when users make redundant changes.
@Observable
public final class LiveQuery<Results>: Sendable where Results: Sendable {
/// The query’s mutable state.
Expand All @@ -95,66 +111,82 @@ public final class LiveQuery<Results>: Sendable where Results: Sendable {

/// The task that handles inputs.
var inputHandlingTask: Task<Void, Never>?

/// The task that iterates the current query fragment’s result updates.
var resultUpdatesTask: Task<Void, Never>?

/// The generation of the current query fragment’s result updates.
///
/// This is incremented each time result updates start for a new query fragment. Result updates only change the
/// query’s state if their generation matches this one.
var resultUpdatesGeneration: UInt64 = 0
}


/// A mutex that synchronizes access to the query’s mutable state.
private let stateMutex = Mutex(State())

/// A continuation used to yield query fragment changes to the input handling task.
private let queryFragmentContinuation: AsyncStream<String>.Continuation

/// The results producer used to generate results.
private let resultsProducer: any LiveQueryResultsProducer<Results>
/// The producer used to generate result updates.
private let resultUpdatesProducer: any LiveQueryResultUpdatesProducer<Results>


/// Creates a live query with the specified results producer.
/// Creates a live query with the specified result updates producer.
///
/// - Parameter resultsProducer: The producer used to generate results.
public init(resultsProducer: some LiveQueryResultsProducer<Results>) {
self.resultsProducer = resultsProducer
/// Each time the query fragment changes, the live query iterates the result updates for the new query fragment,
/// updating ``results`` with each value. It cancels its iteration of the previous query fragment’s result updates.
///
/// - Parameter resultUpdatesProducer: The producer used to generate result updates.
public init(resultUpdatesProducer: some LiveQueryResultUpdatesProducer<Results>) {
self.resultUpdatesProducer = resultUpdatesProducer

let (queryFragmentStream, queryFragmentContinuation) = AsyncStream<String>.makeStream()
self.queryFragmentContinuation = queryFragmentContinuation

let queryFragmentValues = queryFragmentStream.schedule(with: resultsProducer.schedulingStrategy)
let queryFragmentValues = queryFragmentStream.schedule(with: resultUpdatesProducer.schedulingStrategy)
let task = Task { [weak self] in
for await queryFragment in queryFragmentValues {
guard let self else {
return
}

do {
let results = try await resultsProducer.results(forQueryFragment: queryFragment)

_$observationRegistrar.willSet(self, keyPath: \.lastError)
_$observationRegistrar.willSet(self, keyPath: \.results)
stateMutex.withLock { state in
state.results = results
state.lastError = nil
}
_$observationRegistrar.didSet(self, keyPath: \.results)
_$observationRegistrar.didSet(self, keyPath: \.lastError)
} catch {
withMutation(keyPath: \.lastError) {
stateMutex.withLock { $0.lastError = error }
}
}
startResultUpdates(forQueryFragment: queryFragment)
}
}

stateMutex.withLock { $0.inputHandlingTask = task }
}


/// Creates a live query with the specified results producer.
///
/// Each time the query fragment changes, the live query produces results for the new query fragment. If results for
/// the previous query fragment are still being produced, the live query cancels their production and discards them.
///
/// - Parameter resultsProducer: The producer used to generate results.
public convenience init(resultsProducer: some LiveQueryResultsProducer<Results>) {
self.init(resultUpdatesProducer: resultsProducer)
}


deinit {
stateMutex.withLock { $0.inputHandlingTask?.cancel() }
stateMutex.withLock { state in
state.inputHandlingTask?.cancel()
state.resultUpdatesTask?.cancel()
}
queryFragmentContinuation.finish()
}


/// The current query fragment.
///
/// Updates trigger result production based on the scheduling strategy.
/// Updates trigger result production based on the scheduling strategy. If the producer’s
/// ``LiveQueryResultUpdatesProducer/canonicalQueryFragment(from:)`` returns `nil` for the new value, the update
/// doesn’t trigger result production. The query keeps its results, and if the previous query fragment’s result
/// updates haven’t finished, the query keeps iterating them. With the default canonicalization, this happens
/// when the query fragment is empty or contains only whitespace.
public var queryFragment: String {
get {
access(keyPath: \.queryFragment)
Expand All @@ -166,7 +198,7 @@ public final class LiveQuery<Results>: Sendable where Results: Sendable {
stateMutex.withLock { $0.queryFragment = newValue }
}

if let canonicalQueryFragment = resultsProducer.canonicalQueryFragment(from: newValue) {
if let canonicalQueryFragment = resultUpdatesProducer.canonicalQueryFragment(from: newValue) {
queryFragmentContinuation.yield(canonicalQueryFragment)
}
}
Expand All @@ -185,6 +217,92 @@ public final class LiveQuery<Results>: Sendable where Results: Sendable {
access(keyPath: \.lastError)
return stateMutex.withLock(\.lastError)
}


/// Starts iterating the result updates for a query fragment, cancelling the previous fragment’s result updates.
///
/// - Parameter queryFragment: The canonical query fragment whose result updates are iterated.
private func startResultUpdates(forQueryFragment queryFragment: String) {
let resultUpdates = resultUpdatesProducer.resultUpdates(forQueryFragment: queryFragment)

stateMutex.withLock { state in
state.resultUpdatesTask?.cancel()
state.resultUpdatesGeneration += 1

let generation = state.resultUpdatesGeneration
state.resultUpdatesTask = Task { [weak self] in
do {
for try await results in resultUpdates {
// Stop iterating once we’re deallocated, even if the sequence ignores cancellation
guard let self else {
return
}

update(results: results, generation: generation)
}
} catch {
self?.update(error: error, generation: generation)
}
}
}
}


/// Sets the query’s results and clears its last error if the generation is current.
///
/// - Parameters:
/// - results: The new results.
/// - generation: The generation of the result updates that produced the results.
private func update(results: Results, generation: UInt64) {
// Check the generation before notifying observers so that rejected writes don’t cause spurious notifications.
// We check again when writing, because the generation can change in between.
guard isCurrent(generation) else {
return
}

_$observationRegistrar.willSet(self, keyPath: \.lastError)
_$observationRegistrar.willSet(self, keyPath: \.results)
stateMutex.withLock { state in
guard state.resultUpdatesGeneration == generation else {
return
}

state.results = results
state.lastError = nil
}
_$observationRegistrar.didSet(self, keyPath: \.results)
_$observationRegistrar.didSet(self, keyPath: \.lastError)
}


/// Sets the query’s last error if the generation is current.
///
/// - Parameters:
/// - error: The error that occurred.
/// - generation: The generation of the result updates that produced the error.
private func update(error: any Error, generation: UInt64) {
guard isCurrent(generation) else {
return
}

withMutation(keyPath: \.lastError) {
stateMutex.withLock { state in
guard state.resultUpdatesGeneration == generation else {
return
}

state.lastError = error
}
}
}


/// Returns whether the specified generation is the generation of the current query fragment’s result updates.
///
/// - Parameter generation: The generation to check.
private func isCurrent(_ generation: UInt64) -> Bool {
return stateMutex.withLock { $0.resultUpdatesGeneration == generation }
}
}


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//
// LiveQueryResultUpdatesProducer.swift
// DevFoundation
//
// Created by Prachi Gauriar on 11/24/2026.
//

import Foundation

/// A type that produces a sequence of result updates for query fragments.
///
/// Conform to this protocol when a query fragment’s results can change after they’re first produced, like a search
/// over local data that should update when the data does. ``LiveQuery`` iterates the sequence for the latest query
/// fragment and updates its results each time the sequence produces a value. When the query fragment changes, the live
/// query cancels its iteration of the previous fragment’s sequence.
///
/// For example, a producer can return a database observation that produces the current search results, then new
/// results each time the database changes:
///
/// struct NoteSearchProducer: LiveQueryResultUpdatesProducer {
/// let noteStore: NoteStore
///
/// var schedulingStrategy: LiveQuerySchedulingStrategy {
/// .passthrough
/// }
///
/// func resultUpdates(
/// forQueryFragment queryFragment: String
/// ) -> some AsyncSequence<[Note], any Error> & Sendable {
/// noteStore.observeNotes(matching: queryFragment)
/// }
/// }
///
/// let liveQuery = LiveQuery(resultUpdatesProducer: NoteSearchProducer(noteStore: noteStore))
///
/// If results don’t change after they’re produced, conform to ``LiveQueryResultsProducer`` instead. It refines this
/// protocol, providing a default implementation of ``resultUpdates(forQueryFragment:)`` that produces results once.
public protocol LiveQueryResultUpdatesProducer<Results>: Sendable {
/// The type of results that instances produce.
associatedtype Results: Sendable

/// The type of sequence that instances return for each query fragment.
associatedtype ResultUpdates: AsyncSequence<Results, any Error> & Sendable

/// The strategy used to schedule result production.
var schedulingStrategy: LiveQuerySchedulingStrategy { get }

/// Returns a canonical form of the query fragment, or `nil` if it’s invalid.
///
/// Conforming types can use this function to sanitize or validate query fragments before producing results. The
/// default implementation trims whitespace, collapses multiple spaces into one, and returns `nil` for empty
/// strings.
///
/// When this function returns `nil`, live queries don’t produce results for the query fragment. They keep their
/// results, and keep iterating the previous query fragment’s result updates if they haven’t finished.
///
/// - Parameter queryFragment: The query fragment to canonicalize.
func canonicalQueryFragment(from queryFragment: String) -> String?

/// Returns a sequence of results for the specified query fragment.
///
/// The sequence should produce the query fragment’s current results first, followed by new results each time they
/// change. Live queries cancel their iteration of the sequence when the query fragment changes, so the sequence
/// should stop producing values when it’s cancelled.
///
/// - Parameter queryFragment: A canonical query fragment. Live queries ensure this is already canonicalized before
/// calling this function.
func resultUpdates(forQueryFragment queryFragment: String) -> ResultUpdates
}


extension LiveQueryResultUpdatesProducer {
public func canonicalQueryFragment(from queryFragment: String) -> String? {
let canonicalFragment = queryFragment.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.joined(separator: " ")

return canonicalFragment.isEmpty ? nil : canonicalFragment
}
}
Loading
Loading