// A table whose definition says `live: {every: seconds}` keeps its list and // its pages current by itself: while one is on screen and the app is in // front, it reads again on that cadence, in place, keeping what it shows // until the answer lands. Off screen, or with the app behind another, nothing // is read; coming back starts the cadence again from a full pause. // // One read at a time: the next pause starts only once the last read answered, // so a slow store is never asked twice at once. This replaces the Devices // list's own poll (#1256) for any table that names a cadence; a sync that // names the table still reads it again through `recordsRevision` as before. import SwiftUI extension View { /// Runs `read` every `live.interval` while this view is on screen and its /// scene is active; nothing when `live` is nil. func readingLive(_ live: LiveReading?, read: @escaping @MainActor () async -> Void) -> some View { modifier(LiveReadingModifier(live: live, read: read)) } } struct LiveReadingModifier: ViewModifier { let live: LiveReading? let read: @MainActor () async -> Void @Environment(\.scenePhase) private var scenePhase @State private var onScreen = false private struct Ticking: Equatable { // The pause, not the cadence: a NaN `every` never equals itself, so // keyed on it the task would restart on every redraw and never read. var interval: Duration? var running: Bool } func body(content: Content) -> some View { content .onAppear { onScreen = true } .onDisappear { onScreen = false } .task(id: Ticking(interval: live?.interval, running: onScreen && scenePhase == .active)) { guard let live, onScreen, scenePhase == .active else { return } await Self.tick(every: live.interval, read: read) } } /// Pauses `every`, then reads, until the task is cancelled; a pause that /// is cancelled ends it without reading. `sleep` is the pause, so a test /// can count the reads without waiting on a clock. static func tick( every interval: Duration, sleep: (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, read: @MainActor () async -> Void ) async { while !Task.isCancelled { do { try await sleep(interval) } catch { return } guard !Task.isCancelled else { return } await read() } } }