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.
This commit is contained in:
Gwendal Roué committed 2021-10-18 08:41:44 +02:00
1 parent e4bfea8bcc
commit 6a980f90da
4 files changed
+81 -63

No files matched your search

@@ -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
@@ -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<Int> {
/// 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<Value, Error>
}
/// 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<Int> {
/// 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<Query: Queryable>: DynamicProperty {
if query != newValue {
// Stop tracking, and tell SwiftUI about the update
objectWillChange.send()
task?.cancel()
task = nil
cancellable = nil
}
}
}
private var task: Task<Void, Error>?
private var cancellable: AnyCancellable?
init() { }
@@ -167,18 +166,23 @@ struct Query<Query: Queryable>: 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
})
}
}
}
@@ -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
/// <https://forums.swift.org/t/52862>
@State private var missingContent = true
// If you want to define the query on initialization, you will prefer:
//
// @Query<PlayerRequest> 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)
}
}
@@ -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()
}