From 6a980f90da2ef97ff5830fcb587c575d38d8d9a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 18 Oct 2021 08:41:44 +0200 Subject: [PATCH] Async sequence is unsuitable for preventing flash of missing content See https://forums.swift.org/t/52862 for a longer explanation. Fortunately, we can base @Query on Combine publishers, which do not have this problem. --- .../GRDBAsyncDemo/PlayerRequest.swift | 23 ++++++-- .../GRDBAsyncDemo/GRDBAsyncDemo/Query.swift | 48 ++++++++-------- .../GRDBAsyncDemo/Views/AppView.swift | 56 ++++++++----------- .../GRDBCombineDemo/PlayerRequest.swift | 17 +++++- 4 files changed, 81 insertions(+), 63 deletions(-) diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift index 21454fe4c..20c275d64 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift @@ -1,8 +1,18 @@ +import Combine import GRDB -/// A player request defines how to feed the player list. +/// A player request can be used with the `@Query` property wrapper in order to +/// feed a view with a list of players. /// -/// It can be used with the `@Query` property wrapper. +/// For example: +/// +/// struct MyView: View { +/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player] +/// +/// var body: some View { +/// List(players) { player in ... ) +/// } +/// } struct PlayerRequest: Queryable { enum Ordering { case byScore @@ -15,13 +25,16 @@ struct PlayerRequest: Queryable { static var defaultValue: [Player] { [] } - func values(in appDatabase: AppDatabase) -> AsyncValueObservation<[Player]> { - // Build the async sequence from the general-purpose read-only access + func valuePublisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { + // Build the publisher from the general-purpose read-only access // granted by `appDatabase.databaseReader`. // Some apps will prefer to call a dedicated method of `appDatabase`. ValueObservation .trackingConstantRegion(fetchValue(_:)) - .values(in: appDatabase.databaseReader, scheduling: .immediate) + .publisher( + in: appDatabase.databaseReader, + scheduling: .immediate) // Feed the view without delay + .eraseToAnyPublisher() } // This method is not required by Queryable, but it makes it easier diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Query.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Query.swift index 63766b4d1..d79aa4b00 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Query.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Query.swift @@ -28,6 +28,7 @@ // You can copy this file into your project, source code and license. // +import Combine import SwiftUI /// The environment key that lets SwiftUI access the database. @@ -66,24 +67,22 @@ extension EnvironmentValues { /// struct PlayerCount: Queryable { /// static var defaultValue: Int { 0 } /// -/// func values(in appDatabase: AppDatabase) -> AsyncValueObservation { +/// func valuePublisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { /// ValueObservation /// .trackingConstantRegion(Player.fetchCount) -/// .values(in: appDatabase.databaseReader, scheduling: .immediate) +/// .publisher(in: appDatabase.databaseReader, scheduling: .immediate) +/// .eraseToAnyPublisher() /// } /// } protocol Queryable: Equatable { - /// The type of the sequence of database values - associatedtype Sequence: AsyncSequence - - /// The type of the database values - typealias Value = Sequence.Element + /// The type of the fetched value + associatedtype Value /// The default value, used whenever the database is not available static var defaultValue: Value { get } - /// Returns an asynchronous sequence of database values. - func values(in appDatabase: AppDatabase) -> Sequence + /// Returns a publisher of database values + func valuePublisher(in appDatabase: AppDatabase) -> AnyPublisher } /// The property wrapper that tells SwiftUI about changes in the database. @@ -95,10 +94,11 @@ protocol Queryable: Equatable { /// struct PlayerCount: Queryable { /// static var defaultValue: Int { 0 } /// -/// func values(in appDatabase: AppDatabase) -> AsyncValueObservation { +/// func valuePublisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { /// ValueObservation /// .trackingConstantRegion(Player.fetchCount) -/// .values(in: appDatabase.databaseReader, scheduling: .immediate) +/// .publisher(in: appDatabase.databaseReader, scheduling: .immediate) +/// .eraseToAnyPublisher() /// } /// } /// @@ -152,12 +152,11 @@ struct Query: DynamicProperty { if query != newValue { // Stop tracking, and tell SwiftUI about the update objectWillChange.send() - task?.cancel() - task = nil + cancellable = nil } } } - private var task: Task? + private var cancellable: AnyCancellable? init() { } @@ -167,18 +166,23 @@ struct Query: DynamicProperty { return } - guard task == nil else { + guard cancellable == nil else { // Already tracking return } - task = Task { @MainActor in - for try await value in query.values(in: appDatabase) { - if Task.isCancelled { break } - self.objectWillChange.send() - self.value = value - } - } + cancellable = query + .valuePublisher(in: appDatabase) + .sink( + receiveCompletion: { _ in + // Ignore errors + }, + receiveValue: { [weak self] value in + guard let self = self else { return } + // Tell SwiftUI about the new value + self.objectWillChange.send() + self.value = value + }) } } } diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift index f68e18906..60a215a80 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift @@ -14,10 +14,6 @@ struct AppView: View { /// Tracks the presentation of the player creation sheet. @State private var newPlayerIsPresented = false - /// Workaround "flash of missing content" with Swift async/await - /// - @State private var missingContent = true - // If you want to define the query on initialization, you will prefer: // // @Query private var players: [Player] @@ -28,37 +24,31 @@ struct AppView: View { var body: some View { NavigationView { - if missingContent { - EmptyView().onChange(of: players) { players in - missingContent = false - } - } else { - PlayerList(players: players) - .navigationBarTitle(Text(missingContent ? "" : "\(players.count) Players")) - .navigationBarItems( - leading: HStack { - EditButton() - newPlayerButton - }, - trailing: ToggleOrderingButton( - ordering: $players.ordering, - willChange: { - // onChange(of: $players.wrappedValue.ordering) - // reveals a bug in SwiftUI: the List remains in - // editing mode if the editMode is changed during - // the animation of the list content. - // Word around: stop editing *before* the ordering - // is changed, and the list content is updated. - stopEditing() - })) - .toolbar { toolbarContent } - .onChange(of: players) { players in - if players.isEmpty { + PlayerList(players: players) + .navigationBarTitle(Text("\(players.count) Players")) + .navigationBarItems( + leading: HStack { + EditButton() + newPlayerButton + }, + trailing: ToggleOrderingButton( + ordering: $players.ordering, + willChange: { + // onChange(of: $players.wrappedValue.ordering) + // reveals a bug in SwiftUI: the List remains in + // editing mode if the editMode is changed during + // the animation of the list content. + // Word around: stop editing *before* the ordering + // is changed, and the list content is updated. stopEditing() - } + })) + .toolbar { toolbarContent } + .onChange(of: players) { players in + if players.isEmpty { + stopEditing() } - .environment(\.editMode, $editMode) - } + } + .environment(\.editMode, $editMode) } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift index e11204b6e..20c275d64 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift @@ -1,9 +1,18 @@ import Combine import GRDB -/// A player request defines how to feed the player list. +/// A player request can be used with the `@Query` property wrapper in order to +/// feed a view with a list of players. /// -/// It can be used with the `@Query` property wrapper. +/// For example: +/// +/// struct MyView: View { +/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player] +/// +/// var body: some View { +/// List(players) { player in ... ) +/// } +/// } struct PlayerRequest: Queryable { enum Ordering { case byScore @@ -22,7 +31,9 @@ struct PlayerRequest: Queryable { // Some apps will prefer to call a dedicated method of `appDatabase`. ValueObservation .trackingConstantRegion(fetchValue(_:)) - .publisher(in: appDatabase.databaseReader, scheduling: .immediate) + .publisher( + in: appDatabase.databaseReader, + scheduling: .immediate) // Feed the view without delay .eraseToAnyPublisher() }