Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Sources/ObservableViewModel/View+Observe.swift
Original file line number Diff line number Diff line change
@@ -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()
}
}
}
50 changes: 50 additions & 0 deletions Sources/ObservableViewModel/ViewModel+Bind.swift
Original file line number Diff line number Diff line change
@@ -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<Value: Sendable>(
_ stream: AsyncStream<Value>,
to keyPath: WritableKeyPath<State, Value> & 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<Value: Sendable>(
_ stream: AsyncThrowingStream<Value, any Error>,
to keyPath: WritableKeyPath<State, Value> & 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: AsyncSequence & Sendable>(
_ sequence: Sequence,
to keyPath: WritableKeyPath<State, Sequence.Element> & Sendable
) async throws(Sequence.Failure) where Sequence.Element: Sendable {
for try await value in sequence {
await setState(keyPath, value)
}
}
}
8 changes: 8 additions & 0 deletions Sources/ObservableViewModel/ViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
}
Expand Down
144 changes: 144 additions & 0 deletions Tests/ObservableViewModelTests/SubscriptionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import SwiftUI
import Testing
import FactoryKit
@testable import ObservableViewModel

@DomainActor
protocol Ticker: Sendable {
func ticks() -> AsyncStream<Int>
func laps() -> AsyncStream<Int>
}

@DomainActor
final class FiniteTicker: Ticker {
func ticks() -> AsyncStream<Int> {
AsyncStream { $0.yield(1); $0.yield(2); $0.finish() }
}

func laps() -> AsyncStream<Int> {
AsyncStream { $0.yield(7); $0.finish() }
}
}

extension Container {
var ticker: Factory<any Ticker> { 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<Int>.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<Int, any Error>.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())
}
}
Loading