Update the template screen to use the new(ish) Observation framework. (#4077)

* Update the template screen to use the new(ish) Observation framework.

* Add a variant of deferFulfillment that supports observables.

* Update snapshot fulfilment to work with either a publisher or a stream.
This commit is contained in:
Doug
2025-04-30 16:49:23 +01:00
committed by GitHub
parent 0620bd45fc
commit 61a427b8e5
12 changed files with 297 additions and 25 deletions
@@ -9,4 +9,19 @@ extension AsyncSequence {
func first() async rethrows -> Self.Element? {
try await first { _ in true }
}
/// Type-erases the sequence into a newly constructed asynchronous stream. This is useful until
/// we drop support for iOS 17, at which point we can replace this with `any AsyncSequence`.
@available(iOS, deprecated: 18.0, message: "Use `any AsyncSequence` instead.")
func eraseToStream() -> AsyncStream<Element> {
var asyncIterator = makeAsyncIterator()
return AsyncStream<Element> {
do {
return try await asyncIterator.next()
} catch {
MXLog.warning("Stopping stream: \(error)")
return nil
}
}
}
}
@@ -0,0 +1,37 @@
//
// Copyright 2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Foundation
extension Observable {
/// Creates an async stream for the specified property on this object. We probably won't need this once SE-0475 is available:
/// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0475-observed.md
///
/// - Parameter property: The key path to the property you would like to observe.
func observe<Value>(_ property: KeyPath<Self, Value>) -> AsyncStream<Value> {
AsyncStream { continuation in
var isActive = true
@Sendable func observe() {
let value = withObservationTracking {
self[keyPath: property]
} onChange: {
// Dispatch the update as this is willSet not didSet.
DispatchQueue.main.async {
guard isActive else { return }
observe()
}
}
continuation.yield(value)
}
continuation.onTermination = { _ in isActive = false }
observe()
}
}
}
@@ -24,21 +24,26 @@ struct SnapshotPerceptualPrecisionPreferenceKey: PreferenceKey {
}
}
struct FulfillmentPublisherEquatableWrapper: Equatable {
let publisher: AnyPublisher<Bool, Never>?
// Publisher equatability complicates things but, luckily, we're only interesting in them changing from nil
static func == (lhs: FulfillmentPublisherEquatableWrapper, rhs: FulfillmentPublisherEquatableWrapper) -> Bool {
lhs.publisher != nil && rhs.publisher != nil
}
}
struct SnapshotFulfillmentPreferenceKey: PreferenceKey {
static var defaultValue: Wrapper?
struct SnapshotFulfillmentPublisherPreferenceKey: PreferenceKey {
static var defaultValue: FulfillmentPublisherEquatableWrapper?
static func reduce(value: inout FulfillmentPublisherEquatableWrapper?, nextValue: () -> FulfillmentPublisherEquatableWrapper?) {
static func reduce(value: inout Wrapper?, nextValue: () -> Wrapper?) {
value = nextValue()
}
enum Source {
case publisher(AnyPublisher<Bool, Never>)
case stream(AsyncStream<Bool>)
}
struct Wrapper: Equatable {
let id = UUID()
let source: Source
static func == (lhs: Wrapper, rhs: Wrapper) -> Bool {
lhs.id == rhs.id // Not ideal, but it's good enough for snapshots.
}
}
}
extension SwiftUI.View {
@@ -47,7 +52,7 @@ extension SwiftUI.View {
/// These preferences can then be retrieved and used elsewhere in your view hierarchy.
///
/// - Parameters:
/// - delay: The delay time in seconds that you want to set as a preference to the View.
/// - expect: A publisher that indicates when the preview is ready for snapshotting.
/// - precision: The percentage of pixels that must match.
/// - perceptualPrecision: The percentage a pixel must match the source pixel to be considered a match. 98-99% mimics the precision of the human eye.
func snapshotPreferences(expect fulfillmentPublisher: (any Publisher<Bool, Never>)? = nil,
@@ -55,6 +60,22 @@ extension SwiftUI.View {
perceptualPrecision: Float = 0.98) -> some SwiftUI.View {
preference(key: SnapshotPrecisionPreferenceKey.self, value: precision)
.preference(key: SnapshotPerceptualPrecisionPreferenceKey.self, value: perceptualPrecision)
.preference(key: SnapshotFulfillmentPublisherPreferenceKey.self, value: FulfillmentPublisherEquatableWrapper(publisher: fulfillmentPublisher?.eraseToAnyPublisher()))
.preference(key: SnapshotFulfillmentPreferenceKey.self, value: fulfillmentPublisher.map { SnapshotFulfillmentPreferenceKey.Wrapper(source: .publisher($0.eraseToAnyPublisher())) })
}
/// Use this modifier when you want to apply snapshot-specific preferences,
/// like delay and precision, to the view.
/// These preferences can then be retrieved and used elsewhere in your view hierarchy.
///
/// - Parameters:
/// - expect: A stream that indicates when the preview is ready for snapshotting.
/// - precision: The percentage of pixels that must match.
/// - perceptualPrecision: The percentage a pixel must match the source pixel to be considered a match. 98-99% mimics the precision of the human eye.
func snapshotPreferences(expect fulfillmentStream: AsyncStream<Bool>? = nil,
precision: Float = 1.0,
perceptualPrecision: Float = 0.98) -> some SwiftUI.View {
preference(key: SnapshotPrecisionPreferenceKey.self, value: precision)
.preference(key: SnapshotPerceptualPrecisionPreferenceKey.self, value: perceptualPrecision)
.preference(key: SnapshotFulfillmentPreferenceKey.self, value: fulfillmentStream.map { SnapshotFulfillmentPreferenceKey.Wrapper(source: .stream($0)) })
}
}
@@ -48,6 +48,39 @@ extension XCTestCase {
}
}
/// XCTest utility that assists in observing an async stream, deferring the fulfilment and results until some condition has been met.
/// - Parameters:
/// - asyncStream: The stream to wait on.
/// - timeout: A timeout after which we give up.
/// - message: An optional custom expectation message
/// - until: callback that evaluates outputs until some condition is reached
/// - Returns: The deferred fulfilment to be executed after some actions and that returns the result of the publisher.
func deferFulfillment<Value>(_ asyncStream: AsyncStream<Value>,
timeout: TimeInterval = 10,
message: String? = nil,
until condition: @escaping (Value) -> Bool) -> DeferredFulfillment<Value> {
var result: Result<Value, Error>?
let expectation = expectation(description: message ?? "Awaiting stream")
var hasFulfilled = false
let task = Task {
for await value in asyncStream {
if condition(value), !hasFulfilled {
result = .success(value)
expectation.fulfill()
hasFulfilled = true
}
}
}
return DeferredFulfillment<Value> {
await self.fulfillment(of: [expectation], timeout: timeout)
task.cancel()
let unwrappedResult = try XCTUnwrap(result, "Awaited stream did not produce any output")
return try unwrappedResult.get()
}
}
/// XCTest utility that assists in subscribing to a publisher and deferring the fulfilment and results until some other actions have been performed.
/// - Parameters:
/// - publisher: The publisher to wait on.
@@ -8,7 +8,8 @@
import Combine
import Foundation
/// A common ViewModel implementation for handling of `State` and `ViewAction`s
/// A common ViewModel implementation for handling of `State` and `ViewAction`s. This original version
/// is implemented using SwiftUI's original `ObservableObject` and `@Published` pattern.
///
/// Generic type State is constrained to the BindableState protocol in that it may contain (but doesn't have to)
/// a specific portion of state that can be safely bound to.
@@ -0,0 +1,89 @@
//
// Copyright 2022-2024 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Combine
import Foundation
import Observation
/// A common ViewModel implementation for handling of `State` and `ViewAction`s. Version 2 of this state
/// store has been re-written to use Swift's new Observation framework.
///
///
/// Generic type State is constrained to the BindableState protocol in that it may contain (but doesn't have to)
/// a specific portion of state that can be safely bound to.
/// If we decide to add more features to our state management (like doing state processing off the main thread)
/// we can do it in this centralised place.
@MainActor
class StateStoreViewModelV2<State: BindableState, ViewAction> {
/// For storing subscription references.
///
/// Left as public for `ViewModel` implementations convenience.
var cancellables = Set<AnyCancellable>()
/// Constrained interface for passing to Views.
var context: Context
var state: State {
get { context.viewState }
set { context.viewState = newValue }
}
init(initialViewState: State, mediaProvider: MediaProviderProtocol? = nil) {
context = Context(initialViewState: initialViewState, mediaProvider: mediaProvider)
context.viewModel = self
}
/// Override to handles incoming `ViewAction`s from the `ViewModel`.
/// - Parameter viewAction: The `ViewAction` to be processed in `ViewModel` implementation.
func process(viewAction: ViewAction) {
// Default implementation, -no-op
}
// MARK: - Context
/// A constrained and concise interface for interacting with the ViewModel.
///
/// This class is closely bound to`StateStoreViewModel`. It provides the exact interface the view should need to interact
/// ViewModel (as modelled on our previous template architecture with the addition of two-way binding):
/// - The ability read/observe view state
/// - The ability to send view events
/// - The ability to bind state to a specific portion of the view state safely.
/// This class was brought about a little bit by necessity. The most idiomatic way of interacting with SwiftUI is via `@Published`
/// properties which which are property wrappers and therefore can't be defined within protocols.
/// A similar approach is taken in libraries like [CombineFeedback](https://github.com/sergdort/CombineFeedback).
/// It provides a nice layer of consistency and also safety. As we are not passing the `ViewModel` to the view directly, shortcuts/hacks
/// can't be made into the `ViewModel`.
@dynamicMemberLookup
@MainActor
@Observable final class Context {
fileprivate weak var viewModel: StateStoreViewModelV2?
/// Get-able property for the `ViewState`
fileprivate(set) var viewState: State
/// An optional image loading service so that views can manage themselves
/// Intentionally non-generic so that it doesn't grow uncontrollably
let mediaProvider: MediaProviderProtocol?
/// Set-able access to the bindable state.
subscript<T>(dynamicMember keyPath: WritableKeyPath<State.BindStateType, T>) -> T {
get { viewState.bindings[keyPath: keyPath] }
set { viewState.bindings[keyPath: keyPath] = newValue }
}
/// Send a `ViewAction` to the `ViewModel` for processing.
/// - Parameter viewAction: The `ViewAction` to send to the `ViewModel`.
func send(viewAction: ViewAction) {
viewModel?.process(viewAction: viewAction)
}
fileprivate init(initialViewState: State, mediaProvider: MediaProviderProtocol?) {
self.viewState = initialViewState
self.mediaProvider = mediaProvider
}
}
}