How to answer
I'd use cursor-based pagination for anything that changes while the user reads it: the server returns a page plus an opaque nextCursor, so inserts and deletes don't cause duplicates or gaps the way offset/limit does. On the client, a @MainActor @Observable paginator owns the items, the cursor and an explicit load state (idle, loading, failed, exhausted); loadNextPage() is async, ignores calls unless it's idle, deduplicates by ID, and discards responses that arrive after a refresh. The UI (SwiftUI rows or UIKit prefetching) only asks for the next page; it never manages flags itself.
Key points (walk-through)
- API contract:
GET /items?cursor=…&limit=20→{ items, nextCursor }, wherenextCursor == nilmeans the end; the cursor encodes the sort key plus a tie-breaker (e.g.createdAt+id), so ordering is stable - Cursor vs offset: offset is fine for static, sortable data with "jump to page 7" needs (search results, admin tables); cursors are better for feeds, chats and anything live. Keyset/cursor queries are also cheaper for the database at depth
- Client state machine:
idle → loading → idle | exhausted | failed;failed → idleonly through an explicit retry;refresh()resets everything and bumps a generation counter so a late response from the old list is dropped - Data flow: trigger (last rows appear / prefetch) →
loadNextPage()→api.items(after: cursor)→ filter out IDs already seen → append → update cursor and state → views re-render through Observation - Trade-offs: page size (bigger = fewer requests but slower first paint; 20–50 typical); prefetch distance; storing pages in memory only vs persisting the first page(s) in SwiftData for instant launch and offline
- Failure modes: duplicate triggers (state guard), items shifting between pages (ID dedupe), errors (a
.failedstate with Retry instead of a stuck spinner), cancellation (a cancelled load returns to.idleso it can be retried), an expired cursor (restart from the first page) - Offline: cache the first page(s) and the cursor; when offline show cached items plus an inline "can't load more" footer
- Testing: Swift Testing with a fake
ItemsAPI(anactorthat returns scripted pages): concurrentloadNextPage()calls produce one request, a duplicate item is filtered, an error sets.failedandretry()recovers,refresh()during a load ignores the stale result
If they dig deeper
Bidirectional cursors (before / after) for chat history. GraphQL Relay-style connections (edges, pageInfo.endCursor, hasNextPage). Link headers in REST. "Load more" button vs infinite scroll (accessibility and footer reachability). Using AsyncSequence to expose pages (for try await page in paginator) for non-UI consumers.
Common pitfalls
An isLoading flag that stays true after an error, so the list silently never loads again. Offset pagination on a live feed. Appending without dedupe. Starting loads from onAppear { Task { } } with no guard. Completion-handler APIs that capture self across threads (not Swift 6-safe); use async APIs on a @MainActor model instead.
How to use it
The paginator model; the API is a Sendable protocol, and the model is main-actor isolated so the UI reads it directly.
struct Page: Sendable { let items: [Item]; let nextCursor: String? }
protocol ItemsAPI: Sendable { func items(after cursor: String?, limit: Int) async throws -> Page }
@MainActor
@Observable
final class PaginatedList {
enum State: Equatable { case idle, loading, failed, exhausted }
private(set) var items: [Item] = []
private(set) var state: State = .idle
private var cursor: String?
private var seen: Set<Item.ID> = []
private var generation = 0 // bumped by refresh; drops stale responses
private let api: any ItemsAPI
init(api: any ItemsAPI) { self.api = api }
func loadNextPage() async {
guard state == .idle else { return } // one request at a time; nothing after the end
state = .loading
let requested = generation
do {
let page = try await api.items(after: cursor, limit: 20)
guard requested == generation else { return }
items += page.items.filter { seen.insert($0.id).inserted } // dedupe shifted items
cursor = page.nextCursor
state = page.nextCursor == nil ? .exhausted : .idle
} catch {
guard requested == generation else { return }
state = error is CancellationError ? .idle : .failed // .failed shows "Retry"
}
}
func retry() async { if state == .failed { state = .idle; await loadNextPage() } }
func refresh() async {
generation += 1
items = []; seen = []; cursor = nil; state = .idle
await loadNextPage()
}
}SwiftUI: .task { await list.loadNextPage() } on the list, the same call from the last rows' .task, .refreshable { await list.refresh() }, and a footer that switches on list.state. UIKit: call it from collectionView(_:prefetchItemsAt:) (see Infinite Scroll Feed).
Best practices
- Prefer cursors for changing data; offsets only for static, random-access lists
- Model loading as an explicit state machine, with one in-flight request
- Deduplicate by ID and drop stale responses after a refresh
- Surface errors with a retry, and the end of the list explicitly
- Persist the first page for instant launch and offline viewing
- Test the paginator with a scripted fake API
Related concepts
- Infinite Scroll Feed, Feed Loading, Networking Pagination, Diffable Data Source, Lazy Loading (SwiftUI), Offline Mode Design