|
| 1 | +#if canImport(SwiftUI) && canImport(Combine) |
| 2 | + |
| 3 | +import SwiftUI |
| 4 | +import Combine |
| 5 | +import ReactiveSwift |
| 6 | + |
| 7 | +@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) |
| 8 | +@propertyWrapper |
| 9 | +public struct LoopBinding<State, Event>: DynamicProperty { |
| 10 | + @ObservedObject |
| 11 | + private var subscription: SwiftUISubscription<State, Event> |
| 12 | + |
| 13 | + private let loop: Loop<State, Event> |
| 14 | + |
| 15 | + @inlinable |
| 16 | + public var wrappedValue: State { |
| 17 | + acknowledgedState |
| 18 | + } |
| 19 | + |
| 20 | + public var projectedValue: LoopBinding<State, Event> { |
| 21 | + self |
| 22 | + } |
| 23 | + |
| 24 | + @usableFromInline |
| 25 | + internal var acknowledgedState: State |
| 26 | + |
| 27 | + public init(_ loop: Loop<State, Event>) { |
| 28 | + // The subscription can be copied without restrictions. |
| 29 | + let subscription = SwiftUISubscription(loop: loop) |
| 30 | + |
| 31 | + self.subscription = subscription |
| 32 | + self.acknowledgedState = subscription.latestValue |
| 33 | + self.loop = loop |
| 34 | + } |
| 35 | + |
| 36 | + public mutating func update() { |
| 37 | + // Move latest value from the subscription only when SwiftUI has requested an update. |
| 38 | + acknowledgedState = subscription.latestValue |
| 39 | + } |
| 40 | + |
| 41 | + public func scoped<ScopedState, ScopedEvent>( |
| 42 | + to value: KeyPath<State, ScopedState>, |
| 43 | + event: @escaping (ScopedEvent) -> Event |
| 44 | + ) -> LoopBinding<ScopedState, ScopedEvent> { |
| 45 | + LoopBinding<ScopedState, ScopedEvent>(loop.scoped(to: value, event: event)) |
| 46 | + } |
| 47 | + |
| 48 | + public func send(_ event: Event) { |
| 49 | + loop.send(event) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +#endif |
0 commit comments