diff --git a/Sources/ObservableViewModel/View+Observe.swift b/Sources/ObservableViewModel/View+Observe.swift new file mode 100644 index 0000000..7dcfd86 --- /dev/null +++ b/Sources/ObservableViewModel/View+Observe.swift @@ -0,0 +1,14 @@ +import SwiftUI + +extension View { + + /// Runs `observe()` on the view model while the view is on screen. + /// + /// SwiftUI starts the method when the view appears and cancels it when + /// the view disappears. A different view model instance starts it again. + public func observe(on viewModel: some ViewModel) -> some View { + task(id: ObjectIdentifier(viewModel)) { + await viewModel.observe() + } + } +} diff --git a/Sources/ObservableViewModel/ViewModel+Bind.swift b/Sources/ObservableViewModel/ViewModel+Bind.swift new file mode 100644 index 0000000..1341632 --- /dev/null +++ b/Sources/ObservableViewModel/ViewModel+Bind.swift @@ -0,0 +1,50 @@ +/// Each `bind` method writes each value of a sequence to one field of the +/// state. It returns when the sequence finishes or the task is cancelled. +/// +/// Each call waits for its sequence, so put two or more calls in a task group: +/// +/// ```swift +/// func observe() async { +/// let ticks = await ticker.ticks() +/// let times = await clock.times() +/// await withDiscardingTaskGroup { group in +/// group.addTask { await self.bind(ticks, to: \.count) } +/// group.addTask { await self.bind(times, to: \.time) } +/// } +/// } +/// ``` +extension ViewModel { + + public func bind( + _ stream: AsyncStream, + to keyPath: WritableKeyPath & Sendable + ) async { + for await value in stream { + await setState(keyPath, value) + } + } + + /// If the stream fails, the method throws the error. The values before + /// the error stay in the state. + public func bind( + _ stream: AsyncThrowingStream, + to keyPath: WritableKeyPath & Sendable + ) async throws { + for try await value in stream { + await setState(keyPath, value) + } + } + + /// Binds any sequence, such as `Observations`. The method throws only + /// the failure type of the sequence, so a sequence that cannot fail + /// needs no `try`. + @available(iOS 18.0, macOS 15.0, *) + public func bind( + _ sequence: Sequence, + to keyPath: WritableKeyPath & Sendable + ) async throws(Sequence.Failure) where Sequence.Element: Sendable { + for try await value in sequence { + await setState(keyPath, value) + } + } +} diff --git a/Sources/ObservableViewModel/ViewModel.swift b/Sources/ObservableViewModel/ViewModel.swift index a1970ec..2a86aaa 100644 --- a/Sources/ObservableViewModel/ViewModel.swift +++ b/Sources/ObservableViewModel/ViewModel.swift @@ -9,10 +9,18 @@ public protocol ViewModel: AnyObject, Observable, Sendable { /// The one property a view reads. It stays on the main actor, because /// SwiftUI reads it from `body` and `body` cannot await. See docs/adr/0001. @MainActor var state: State { get set } + + /// Reads the streams that feed the state, until the task is cancelled. + /// + /// The `observe(on:)` view modifier calls this method. The default does + /// nothing. Write this method in the view model to bind its streams. + func observe() async } extension ViewModel { + public func observe() async {} + /// Writes one field of the state. /// /// Call this from a method that runs on the view model actor. The `await` diff --git a/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift b/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift index 884bc0d..de3db7d 100644 --- a/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift +++ b/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift @@ -53,7 +53,10 @@ public struct ObservableViewModelMacro { } guard let state = declaration.property(named: "state") else { throw MacroError( - "@ObservableViewModel needs a state property. Add @MainActor var state = MyState().", + """ + @ObservableViewModel needs a state property that conforms to ViewState. + Add @MainActor var state = MyState(). + """, id: "missingState" ) } diff --git a/Tests/ObservableViewModelTests/SubscriptionTests.swift b/Tests/ObservableViewModelTests/SubscriptionTests.swift new file mode 100644 index 0000000..28ddbd0 --- /dev/null +++ b/Tests/ObservableViewModelTests/SubscriptionTests.swift @@ -0,0 +1,144 @@ +import SwiftUI +import Testing +import FactoryKit +@testable import ObservableViewModel + +@DomainActor +protocol Ticker: Sendable { + func ticks() -> AsyncStream + func laps() -> AsyncStream +} + +@DomainActor +final class FiniteTicker: Ticker { + func ticks() -> AsyncStream { + AsyncStream { $0.yield(1); $0.yield(2); $0.finish() } + } + + func laps() -> AsyncStream { + AsyncStream { $0.yield(7); $0.finish() } + } +} + +extension Container { + var ticker: Factory { self { FiniteTicker() }.scope(.cached) } +} + +struct TickState: ViewState { + var count = 0 + var laps = 0 +} + +@ViewModelActor +@Observable +@ObservableViewModel(\.ticker) +final class TickViewModel { + @MainActor var state: TickState + + func observe() async { + let ticks = await ticker.ticks() + let laps = await ticker.laps() + await withDiscardingTaskGroup { group in + group.addTask { await self.bind(ticks, to: \.count) } + group.addTask { await self.bind(laps, to: \.laps) } + } + } +} + +struct StreamError: Error {} + +@MainActor +@Observable +final class Source { + var value = 1 +} + +/// Waits until the condition is true, or gives up after many turns. +@MainActor +func waitUntil(_ condition: () -> Bool) async { + for _ in 0 ..< 10_000 { + if condition() { return } + await Task.yield() + } +} + +@Suite("Observe") +@MainActor +struct ObserveTests { + + @Test + func theDefaultObserveReturnsAtOnce() async { + await CounterViewModel().observe() + } + + @Test + func anOverrideBindsEachStream() async { + let viewModel = TickViewModel() + + await viewModel.observe() + + #expect(viewModel.state.count == 2) + #expect(viewModel.state.laps == 7) + } + + @Test + func aGenericCallerReachesTheOverride() async { + // The modifier sees only `some ViewModel`. This call takes the same path. + func observe(_ viewModel: some ViewModel) async { await viewModel.observe() } + let viewModel = TickViewModel() + + await observe(viewModel) + + #expect(viewModel.state.count == 2) + } + + @Test + func cancellingTheTaskStopsTheBinding() async { + let (stream, continuation) = AsyncStream.makeStream() + let viewModel = TickViewModel() + + let task = Task { await viewModel.bind(stream, to: \.count) } + continuation.yield(5) + await waitUntil { viewModel.state.count == 5 } + task.cancel() + await task.value + + // The stream is still open. Only the cancellation can end the task. + #expect(viewModel.state.count == 5) + } + + @Test + func aThrowingStreamKeepsItsValuesAndThrowsItsError() async { + let (stream, continuation) = AsyncThrowingStream.makeStream() + let viewModel = TickViewModel() + + continuation.yield(4) + continuation.finish(throwing: StreamError()) + + await #expect(throws: StreamError.self) { + try await viewModel.bind(stream, to: \.count) + } + #expect(viewModel.state.count == 4) + } + + @Test @available(iOS 26.0, macOS 26.0, *) + func observationsBindWithoutTry() async { + let source = Source() + let viewModel = TickViewModel() + + let task = Task { await viewModel.bind(Observations { source.value }, to: \.count) } + await waitUntil { viewModel.state.count == 1 } + source.value = 3 + await waitUntil { viewModel.state.count == 3 } + task.cancel() + await task.value + + #expect(viewModel.state.count == 3) + } + + @Test + func theModifierAcceptsAnyViewModel() { + _ = EmptyView().observe(on: TickViewModel()) + _ = EmptyView().observe(on: CounterViewModel()) + } +}