Fix the flakey preview tests. (#4329)

* Try fix the flakey preview tests with a low priority task…

* Try RunLoop.current.perform

* Revert #4321: Use a dispatch queue again. Also fixes the concurrency warning with a Mutex.

The Mutex package is only required for iOS 17, we can remove it when we set the minimum deployment target to iOS 18.
This commit is contained in:
Doug
2025-07-17 12:45:33 +01:00
committed by GitHub
parent ca9d84d1d2
commit 247c7a4617
7 changed files with 100 additions and 25 deletions
@@ -6,6 +6,7 @@
//
import Foundation
import Mutex
extension Observable {
/// Creates an async stream for the specified property on this object. We probably won't need this once SE-0475 is available:
@@ -14,22 +15,22 @@ extension Observable {
/// - 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
let isActive = Mutex(true)
@Sendable func observe() {
let value = withObservationTracking {
self[keyPath: property]
} onChange: {
// Handle the update on the next run loop as this is willSet not didSet.
Task {
guard isActive else { return }
DispatchQueue.main.async {
guard isActive.withLock({ $0 }) else { return }
observe()
}
}
continuation.yield(value)
}
continuation.onTermination = { _ in isActive = false }
continuation.onTermination = { _ in isActive.withLock { $0 = false } }
observe()
}