|
| 1 | +import Foundation |
| 2 | + |
| 3 | +extension Waitable { |
| 4 | + @discardableResult |
| 5 | + public func wait<Value>( |
| 6 | + for keyPath: KeyPath<Self, Value>, |
| 7 | + duration: TimeInterval = 3, |
| 8 | + interval: TimeInterval = 0.1, |
| 9 | + expecting: @escaping (Value) -> Bool |
| 10 | + ) async throws -> Value { |
| 11 | + try await wait( |
| 12 | + for: keyPath, |
| 13 | + interation: 0, |
| 14 | + duration: abs(duration), |
| 15 | + interval: abs(interval), |
| 16 | + expecting: expecting |
| 17 | + ) |
| 18 | + } |
| 19 | + |
| 20 | + @discardableResult |
| 21 | + public func wait<Value: Equatable>( |
| 22 | + for keyPath: KeyPath<Self, Value>, |
| 23 | + duration: TimeInterval = 3, |
| 24 | + interval: TimeInterval = 0.1, |
| 25 | + expecting: Value |
| 26 | + ) async throws -> Value { |
| 27 | + try await wait( |
| 28 | + for: keyPath, |
| 29 | + interation: 0, |
| 30 | + duration: abs(duration), |
| 31 | + interval: abs(interval), |
| 32 | + expecting: { value in |
| 33 | + expecting == value |
| 34 | + } |
| 35 | + ) |
| 36 | + } |
| 37 | + |
| 38 | + private func wait(duration: TimeInterval) async throws { |
| 39 | + try await Task.sleep(nanoseconds: UInt64(1_000_000_000 * abs(duration))) |
| 40 | + } |
| 41 | + |
| 42 | + private func wait<Value>( |
| 43 | + for keyPath: KeyPath<Self, Value>, |
| 44 | + interation: UInt, |
| 45 | + duration: TimeInterval, |
| 46 | + interval: TimeInterval, |
| 47 | + expecting: @escaping (Value) -> Bool |
| 48 | + ) async throws -> Value { |
| 49 | + guard Double(interation) * interval < duration else { |
| 50 | + throw WaitableError.timeout(duration) |
| 51 | + } |
| 52 | + |
| 53 | + let value = self[keyPath: keyPath] |
| 54 | + |
| 55 | + if expecting(value) { |
| 56 | + return value |
| 57 | + } |
| 58 | + |
| 59 | + try await wait(duration: interval) |
| 60 | + |
| 61 | + return try await wait( |
| 62 | + for: keyPath, |
| 63 | + interation: interation + 1, |
| 64 | + duration: duration, |
| 65 | + interval: interval, |
| 66 | + expecting: expecting |
| 67 | + ) |
| 68 | + } |
| 69 | +} |
0 commit comments