diff --git a/.agents/skills/make-feature/SKILL.md b/.agents/skills/make-feature/SKILL.md new file mode 100644 index 0000000..67656fc --- /dev/null +++ b/.agents/skills/make-feature/SKILL.md @@ -0,0 +1,81 @@ +--- +name: make-feature +description: Creates a SwiftUI feature foundation with ObservableViewModel and FactoryKit. Use when creating a feature or its actor, provider, use cases, state, view model, and view. +--- + +# Make a feature + +Create one feature that builds in the target app and connects a view action to observable state. + +## Locate the reference and target + +1. Read the target repository's `AGENTS.md` and package or Xcode configuration. +2. Find the ObservableViewModel checkout, three directories above this skill directory when using the repository copy. +3. Read that checkout's `README.md` and `Demo/ObservableViewModelDemo/MyFeature` Swift files. +4. Identify the target app, feature name, destination, initial state, and first action from the request and existing code. +5. If a required choice remains unclear, ask the user before you create files that depend on it. + +Use the target app's module and naming conventions. +If the app already has a provider or use case for the requested behavior, use it. +Default to an in-memory value when the user requests only a foundation. + +## Create the foundation + +Use this file map unless the app already has an equivalent structure: + +```text +/ + Actor.swift + Domain/ + Provider.swift + GetUseCase.swift + SetUseCase.swift + Container.swift + Presentation/ + ViewModel.swift + .swift +``` + +1. Declare `Actor` as a global actor with a shared instance for domain work. +2. Define a sendable provider protocol with a value stream and an actor-isolated mutation method. +3. Implement the provider with storage on `Actor` and a stream that supports task cancellation. +4. Define get and set use case protocols and implementations that access the provider through FactoryKit. +5. Register the provider and use cases on `Container`. Share the provider instance between reads and writes. +6. Define `State: ViewState` with sendable fields and default values for a no-argument initializer. +7. Add `Equatable` when the view compares or animates the state. +8. Declare the view model with `@ViewModelActor`, `@Observable`, and `@ObservableViewModel` dependency key paths. +9. Declare `@MainActor var state: State` without an initial value or an explicit view model initializer. +10. Bind the value stream in `observe()`, with child tasks in `withDiscardingTaskGroup` for multiple streams. +11. Add an async action with a view-owned task, or a nonisolated action that starts actor-isolated work. +12. Create the SwiftUI view with a private `@State` view model and `.observe(on: viewModel)`. +13. Connect the requested action and state display in the view. +14. Add the files to the app target. +15. If the request includes an app entry point, connect navigation. + +## Concurrency and dependencies + +- Keep domain storage on `Actor`, view model behavior on its global actor, and view state on `MainActor`. +- Make use case protocols `Sendable`. With default main-actor isolation, mark actor-independent use case protocols and implementations `nonisolated`. +- Preserve `Sendable` when you erase an async sequence type, such as `any AsyncSequence & Sendable`. +- Use `await setState` for state changes from the view model actor. +- Use the closure form for a state change that depends on the previous state. +- Register dependency replacements before creating a view model. The macro resolves dependencies during initialization. +- Use `FactoryKit` directly in targets that import it, with a direct package product dependency. +- For a custom container, resolve its dependencies explicitly instead of passing them to the macro. +- Use `Observations` only when the target supports it. The demo requires iOS 26 or macOS 26. +- For older targets, use a cancellation-aware `AsyncStream` with a separate continuation for each subscriber. +- Handle throwing streams in `observe()` and expose the requested error state. +- Keep long-lived observation in the task that `.observe(on:)` manages. + +## Verify and report + +1. Build the target app with its configured Swift language mode and deployment target. +2. Check the first action, the state update, and observation cancellation with a focused test or app run. + For concurrent Swift tests, follow `Tests/ObservableViewModelTests/ConcurrentObservationTests.swift` in the library checkout. + Use FactoryTesting’s `.container` trait for isolated dependencies. + Assert state with `ObservationsShim` and bounded `fulfillment` calls. +3. For library changes in this checkout, run `swift test`. +4. Report the files you created, the connected behavior, and the checks that passed. +5. If a build or runtime check was unavailable, state the limit and the remaining check. + +Example request: “Create an Animals feature with an in-memory animal stream and an action that selects another animal.” diff --git a/.gitignore b/.gitignore index 29a1e94..2683844 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ .build/ .swiftpm/ .DS_Store +DerivedData/ +xcuserdata/ +*.xcuserstate diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4be3f7e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,30 @@ +# Repository guide + +Read [README.md](README.md) for setup and public usage. + +## Create a feature + +When you create a feature with ObservableViewModel, read [.agents/skills/make-feature/SKILL.md](.agents/skills/make-feature/SKILL.md). +Use [Demo/ObservableViewModelDemo/MyFeature](Demo/ObservableViewModelDemo/MyFeature) as the working reference. +Create app features in the requested app target, outside the library's `Sources` directory. + +## Change the library + +- Keep runtime APIs in `Sources/ObservableViewModel` and macro expansion in `Sources/ObservableViewModelMacros`. +- Preserve the explicit actor, `@Observable`, and state declarations that the macro requires. +- Keep view state on `MainActor` and feature behavior on its declared global actor. +- When behavior changes, add or update a test in `Tests/ObservableViewModelTests`. +- When the public pattern changes, update the README, demo, and feature skill together. + +## Verify changes + +Run `swift test` from the repository root for library or macro changes. +For demo changes, build the Xcode project with the command in [README.md](README.md#development). +Use `-destination 'generic/platform=iOS Simulator'` to check its iOS build. +Report the checks you ran and any checks you could not complete. + +## Write documentation + +Use short, active sentences and consistent names. +Check examples against the package's Swift language mode and deployment targets. +State higher OS requirements for APIs such as `Observations`. diff --git a/Demo/ObservableViewModelDemo.xcodeproj/project.pbxproj b/Demo/ObservableViewModelDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..4c407f5 --- /dev/null +++ b/Demo/ObservableViewModelDemo.xcodeproj/project.pbxproj @@ -0,0 +1,389 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 90; + objects = { + +/* Begin PBXBuildFile section */ + 000000000000000000000202 /* ObservableViewModel in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000201 /* ObservableViewModel */; }; + 000000000000000000000205 /* FactoryKit in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000204 /* FactoryKit */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 000000000000000000000120 /* ObservableViewModelDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ObservableViewModelDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 000000000000000000000010 /* ObservableViewModelDemo */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = ObservableViewModelDemo; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 000000000000000130000000 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + files = ( + 000000000000000000000205 /* FactoryKit in Frameworks */, + 000000000000000000000202 /* ObservableViewModel in Frameworks */, + ); + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 000000000000000000000001 = { + isa = PBXGroup; + children = ( + 000000000000000000000010 /* ObservableViewModelDemo */, + 000000000000000000000020 /* Products */, + ); + sourceTree = ""; + }; + 000000000000000000000020 /* Products */ = { + isa = PBXGroup; + children = ( + 000000000000000000000120 /* ObservableViewModelDemo.app */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 000000000000000100000000 /* ObservableViewModelDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = 000000000000000110000000 /* Build configuration list for PBXNativeTarget "ObservableViewModelDemo" */; + buildPhases = ( + 000000000000000120000000 /* Sources */, + 000000000000000130000000 /* Frameworks */, + 000000000000000140000000 /* Resources */, + ); + buildRules = ( + ); + fileSystemSynchronizedGroups = ( + 000000000000000000000010 /* ObservableViewModelDemo */, + ); + name = ObservableViewModelDemo; + packageProductDependencies = ( + 000000000000000000000201 /* ObservableViewModel */, + 000000000000000000000204 /* FactoryKit */, + ); + productName = MyApp; + productReference = 000000000000000000000120 /* ObservableViewModelDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 000000000000000000000000 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2630; + LastUpgradeCheck = 2700; + TargetAttributes = { + 000000000000000100000000 = { + CreatedOnToolsVersion = 26.3; + }; + }; + }; + buildConfigurationList = 000000000000000010000000 /* Build configuration list for PBXProject "ObservableViewModelDemo" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 000000000000000000000001; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + 000000000000000000000200 /* XCLocalSwiftPackageReference ".." */, + 000000000000000000000203 /* XCRemoteSwiftPackageReference "Factory" */, + ); + preferredProjectObjectVersion = 90; + productRefGroup = 000000000000000000000020 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 000000000000000100000000 /* ObservableViewModelDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 000000000000000140000000 /* Resources */ = { + isa = PBXResourcesBuildPhase; + files = ( + ); + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 000000000000000120000000 /* Sources */ = { + isa = PBXSourcesBuildPhase; + files = ( + ); + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 000000000000000011000000 /* Debug configuration for PBXProject "ObservableViewModelDemo" */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + DRIVERKIT_DEPLOYMENT_TARGET = 27.0; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 26.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TVOS_DEPLOYMENT_TARGET = 27.0; + WATCHOS_DEPLOYMENT_TARGET = 27.0; + XROS_DEPLOYMENT_TARGET = 27.0; + }; + name = Debug; + }; + 000000000000000012000000 /* Release configuration for PBXProject "ObservableViewModelDemo" */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DRIVERKIT_DEPLOYMENT_TARGET = 27.0; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 26.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + TVOS_DEPLOYMENT_TARGET = 27.0; + WATCHOS_DEPLOYMENT_TARGET = 27.0; + XROS_DEPLOYMENT_TARGET = 27.0; + }; + name = Release; + }; + 000000000000000111000000 /* Debug configuration for PBXNativeTarget "ObservableViewModelDemo" */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_APP_SANDBOX = YES; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SELECTED_FILES = readonly; + GENERATE_INFOPLIST_FILE = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; + "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = org.example.ObservableViewModelDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + REGISTER_APP_GROUPS = YES; + SDKROOT = auto; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 000000000000000112000000 /* Release configuration for PBXNativeTarget "ObservableViewModelDemo" */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_APP_SANDBOX = YES; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SELECTED_FILES = readonly; + GENERATE_INFOPLIST_FILE = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; + "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = org.example.ObservableViewModelDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + REGISTER_APP_GROUPS = YES; + SDKROOT = auto; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 000000000000000010000000 /* Build configuration list for PBXProject "ObservableViewModelDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000011000000 /* Debug configuration for PBXProject "ObservableViewModelDemo" */, + 000000000000000012000000 /* Release configuration for PBXProject "ObservableViewModelDemo" */, + ); + defaultConfigurationName = Release; + }; + 000000000000000110000000 /* Build configuration list for PBXNativeTarget "ObservableViewModelDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000111000000 /* Debug configuration for PBXNativeTarget "ObservableViewModelDemo" */, + 000000000000000112000000 /* Release configuration for PBXNativeTarget "ObservableViewModelDemo" */, + ); + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 000000000000000000000200 /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 000000000000000000000203 /* XCRemoteSwiftPackageReference "Factory" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/hmlongco/Factory.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 3.3.2; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 000000000000000000000201 /* ObservableViewModel */ = { + isa = XCSwiftPackageProductDependency; + productName = ObservableViewModel; + }; + 000000000000000000000204 /* FactoryKit */ = { + isa = XCSwiftPackageProductDependency; + package = 000000000000000000000203 /* XCRemoteSwiftPackageReference "Factory" */; + productName = FactoryKit; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 000000000000000000000000 /* Project object */; +} diff --git a/Demo/ObservableViewModelDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Demo/ObservableViewModelDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Demo/ObservableViewModelDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Demo/ObservableViewModelDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ObservableViewModelDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..6e3070e --- /dev/null +++ b/Demo/ObservableViewModelDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "4d7ac6f22dfba37481a38bfff53fca0154f7ab6d50809fec8391bad3b72b8549", + "pins" : [ + { + "identity" : "factory", + "kind" : "remoteSourceControl", + "location" : "https://github.com/hmlongco/Factory.git", + "state" : { + "revision" : "5f4ea2bf876fd08db3442af96270424120bd2c70", + "version" : "3.5.3" + } + }, + { + "identity" : "swift-syntax", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swiftlang/swift-syntax.git", + "state" : { + "revision" : "4799286537280063c85a32f09884cfbca301b1a1", + "version" : "602.0.0" + } + } + ], + "version" : 3 +} diff --git a/Demo/ObservableViewModelDemo/Assets.xcassets/AccentColor.colorset/Contents.json b/Demo/ObservableViewModelDemo/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..eb87897 --- /dev/null +++ b/Demo/ObservableViewModelDemo/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Demo/ObservableViewModelDemo/Assets.xcassets/Contents.json b/Demo/ObservableViewModelDemo/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Demo/ObservableViewModelDemo/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Demo/ObservableViewModelDemo/MyApp.swift b/Demo/ObservableViewModelDemo/MyApp.swift new file mode 100644 index 0000000..0c47edd --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyApp.swift @@ -0,0 +1,11 @@ +import SwiftUI + +@main struct MyApp: App { + var body: some Scene { + WindowGroup { + NavigationStack { + MyFeature() + } + } + } +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/Domain/Container.swift b/Demo/ObservableViewModelDemo/MyFeature/Domain/Container.swift new file mode 100644 index 0000000..eb4273d --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/Domain/Container.swift @@ -0,0 +1,25 @@ +import FactoryKit + +extension Container { + + var myFeatureProvider: Factory { + self { + MyFeatureProvider() + } + .singleton + } + + // MARK: UseCase + + var getSomethingUseCase: Factory { + self { + GetSomethingUseCaseImpl() + } + } + + var setSomethingUseCase: Factory { + self { + SetSomethingUseCaseImpl() + } + } +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/Domain/GetSomethingUseCase.swift b/Demo/ObservableViewModelDemo/MyFeature/Domain/GetSomethingUseCase.swift new file mode 100644 index 0000000..d4c3f67 --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/Domain/GetSomethingUseCase.swift @@ -0,0 +1,17 @@ +import FactoryKit + +nonisolated protocol GetSomethingUseCase: Sendable { + var values: any AsyncSequence & Sendable { get async } +} + +nonisolated struct GetSomethingUseCaseImpl: GetSomethingUseCase { + + @MyFeatureActor + @Injected(\.myFeatureProvider) private var myFeatureProvider + + var values: any AsyncSequence & Sendable { + get async { + await myFeatureProvider.something + } + } +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/Domain/MyFeatureProvider.swift b/Demo/ObservableViewModelDemo/MyFeature/Domain/MyFeatureProvider.swift new file mode 100644 index 0000000..bbef7e2 --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/Domain/MyFeatureProvider.swift @@ -0,0 +1,26 @@ +import Observation + +protocol MyFeatureProviding: Sendable { + nonisolated var something: any AsyncSequence & Sendable { get } + @MyFeatureActor func set(something: String) +} + +@MyFeatureActor +@Observable +final class MyFeatureProvider: MyFeatureProviding, Sendable { + + private var currentSomething: String? + nonisolated var something: any AsyncSequence & Sendable { + Observations { @MyFeatureActor in + self.currentSomething + } + .compactMap { $0 } + } + + nonisolated init() { + } + + func set(something: String) { + currentSomething = something + } +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/Domain/SetSomethingUseCase.swift b/Demo/ObservableViewModelDemo/MyFeature/Domain/SetSomethingUseCase.swift new file mode 100644 index 0000000..bcd1eb7 --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/Domain/SetSomethingUseCase.swift @@ -0,0 +1,15 @@ +import FactoryKit + +nonisolated protocol SetSomethingUseCase: Sendable { + func callAsFunction(_ something: String) async +} + +nonisolated struct SetSomethingUseCaseImpl: SetSomethingUseCase { + + @MyFeatureActor + @Injected(\.myFeatureProvider) var myFeatureProvider + + func callAsFunction(_ something: String) async { + await myFeatureProvider.set(something: something) + } +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/MyFeatureActor.swift b/Demo/ObservableViewModelDemo/MyFeature/MyFeatureActor.swift new file mode 100644 index 0000000..2f5a315 --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/MyFeatureActor.swift @@ -0,0 +1,4 @@ +@globalActor +actor MyFeatureActor { + static let shared = MyFeatureActor() +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/Presentation/MyFeature.swift b/Demo/ObservableViewModelDemo/MyFeature/Presentation/MyFeature.swift new file mode 100644 index 0000000..ae130bc --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/Presentation/MyFeature.swift @@ -0,0 +1,30 @@ +import SwiftUI +import ObservableViewModel + +struct MyFeature: View { + + @State private var viewModel = MyFeatureViewModel() + + var body: some View { + VStack(spacing: 16) { + Text(viewModel.state.something) + .font(.largeTitle) + .fontWeight(.bold) + + Button("Generate") { + viewModel.generate() + } + .font(.title) + .fontWeight(.bold) + } + .padding() + .animation(.default, value: viewModel.state) + .observe(on: viewModel) + .navigationTitle("Demo App") + .navigationSubtitle("ObservableViewModel") + } +} + +#Preview { + MyFeature() +} diff --git a/Demo/ObservableViewModelDemo/MyFeature/Presentation/MyFeatureViewModel.swift b/Demo/ObservableViewModelDemo/MyFeature/Presentation/MyFeatureViewModel.swift new file mode 100644 index 0000000..5aeccf9 --- /dev/null +++ b/Demo/ObservableViewModelDemo/MyFeature/Presentation/MyFeatureViewModel.swift @@ -0,0 +1,35 @@ +import Observation +import ObservableViewModel +import FactoryKit + +struct MyFeatureState: ViewState, Equatable { + var something: String = "" +} + +@ViewModelActor +@Observable +@ObservableViewModel( + \.getSomethingUseCase, + \.setSomethingUseCase +) +final class MyFeatureViewModel { + @MainActor var state: MyFeatureState + + func observe() async { + let somethingStream = await getSomethingUseCase.values + + await bind(somethingStream, to: \.something) + } + + nonisolated func generate() { + Task { + await setSomethingUseCase(randomString()) + } + } + + private func randomString() -> String { + let strings = ["🐈", "🦎", "🐕", "🐅", "🐠", "🦒"] + let index = Int.random(in: (0..( _ stream: AsyncStream, to keyPath: WritableKeyPath & Sendable @@ -24,8 +24,9 @@ extension ViewModel { } } - /// If the stream fails, the method throws the error. The values before - /// the error stay in the state. + /// Writes each stream value to the state field until completion, cancellation, or failure. + /// + /// If the stream fails, throws its error and keeps the last state value. public func bind( _ stream: AsyncThrowingStream, to keyPath: WritableKeyPath & Sendable @@ -35,9 +36,10 @@ extension ViewModel { } } - /// 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`. + /// Writes each sequence value to the state field and propagates sequence errors. + /// + /// A sequence with failure type `Never` needs no `try`. + /// The sequence must respond to cancellation for this call to stop when its task is cancelled. @available(iOS 18.0, macOS 15.0, *) public func bind( _ sequence: Sequence, diff --git a/Sources/ObservableViewModel/ViewModel.swift b/Sources/ObservableViewModel/ViewModel.swift index 2a86aaa..fd55982 100644 --- a/Sources/ObservableViewModel/ViewModel.swift +++ b/Sources/ObservableViewModel/ViewModel.swift @@ -2,18 +2,16 @@ import Observation /// A view model that holds main-actor state and routes work to its actor. /// -/// `@ObservableViewModel` adds this conformance. Do not write it by hand. +/// `@ObservableViewModel` adds this conformance. public protocol ViewModel: AnyObject, Observable, Sendable { associatedtype State: ViewState - /// 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. + /// The state that SwiftUI reads synchronously from `body` on the main actor. @MainActor var state: State { get set } - /// Reads the streams that feed the state, until the task is cancelled. + /// Binds the streams that update state until they finish or 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. + /// The `observe(on:)` view modifier calls this method. The default implementation returns immediately. func observe() async } @@ -21,10 +19,9 @@ extension ViewModel { public func observe() async {} - /// Writes one field of the state. + /// Replaces the state field at `keyPath` with `value` on the main actor. /// - /// Call this from a method that runs on the view model actor. The `await` - /// moves the write to the main actor. + /// Use `await` when calling from the view model actor. @MainActor public func setState( _ keyPath: WritableKeyPath, @@ -33,10 +30,10 @@ extension ViewModel { state[keyPath: keyPath] = value } - /// Reads and writes the state in one main-actor step. + /// Runs `body` with mutable state in one main-actor step. /// - /// Use this form for a read-modify-write. A separate read and write cross - /// the actor boundary twice, and another task can run in the gap. + /// Use this form when a change depends on the previous state. + /// Separate reads and writes let another task change state between them. @MainActor public func setState(_ body: sending (inout State) -> Void) { body(&state) diff --git a/Sources/ObservableViewModel/ViewModelActor.swift b/Sources/ObservableViewModel/ViewModelActor.swift index b229164..58f3681 100644 --- a/Sources/ObservableViewModel/ViewModelActor.swift +++ b/Sources/ObservableViewModel/ViewModelActor.swift @@ -1,11 +1,8 @@ /// The default actor for view model behavior. /// -/// Every view model in an app shares this one serial executor, so a view model -/// method must not do slow synchronous work. It routes the work to a dependency -/// that states its own actor. See docs/adr/0003. -/// -/// To split view models across more than one executor, declare another global -/// actor and write that attribute instead. +/// View models marked `@ViewModelActor` share one serial executor. +/// Route slow synchronous work to dependencies with their own isolation. +/// To use another executor, declare a global actor and apply its attribute to the view model. @globalActor public actor ViewModelActor { public static let shared = ViewModelActor() diff --git a/Sources/ObservableViewModel/ViewState.swift b/Sources/ObservableViewModel/ViewState.swift index 0555cce..4e752f8 100644 --- a/Sources/ObservableViewModel/ViewState.swift +++ b/Sources/ObservableViewModel/ViewState.swift @@ -1,8 +1,7 @@ /// The value a view model publishes to its view. /// -/// A view model reads and writes its state across an actor boundary, so the -/// type must be `Sendable`. The macro writes an initializer with a default -/// argument, so the type must also have a no-argument initializer. +/// State crosses actor boundaries and must be `Sendable`. +/// The macro's default `initialState` argument requires a no-argument initializer. public protocol ViewState: Sendable { init() } diff --git a/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift b/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift index de3db7d..72da8f2 100644 --- a/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift +++ b/Sources/ObservableViewModelMacros/ObservableViewModelMacro.swift @@ -1,16 +1,9 @@ import SwiftSyntax import SwiftSyntaxMacros -/// Writes the dependency properties, the initializer, and the conformance. -/// -/// It writes nothing else. Everything it writes is code a developer can write -/// by hand. See docs/adr/0004. +/// Generates dependency properties, an initializer, and `ViewModel` conformance. public struct ObservableViewModelMacro { - /// Reads the property names out of the key path arguments. - /// - /// `\.someUseCase` gives `someUseCase`. The macro never learns the type, - /// so the generated property takes its type by inference. See docs/adr/0002. static func dependencyNames(of node: AttributeSyntax) throws -> [String] { guard let arguments = node.arguments?.as(LabeledExprListSyntax.self) else { return [] } return try arguments.map { argument in @@ -27,16 +20,15 @@ public struct ObservableViewModelMacro { } } - /// Fails the build when the view model does not state what the macro reads. static func checkPreconditions(_ declaration: some DeclGroupSyntax) throws -> String { guard declaration.is(ClassDeclSyntax.self) else { - throw MacroError("@ObservableViewModel applies to a class.", id: "notAClass") + throw MacroError("@ObservableViewModel requires a class.", id: "notAClass") } guard declaration.statedActor != nil else { throw MacroError( """ - @ObservableViewModel needs an actor attribute on this class. \ - Add @ViewModelActor, or another global actor. + @ObservableViewModel requires a global actor attribute on this class. \ + Add @ViewModelActor or another global actor. """, id: "missingActor" ) @@ -44,9 +36,8 @@ public struct ObservableViewModelMacro { guard declaration.hasAttribute("Observable") else { throw MacroError( """ - @ObservableViewModel needs @Observable on this class. \ - A macro cannot add it, because @Observable cannot see a \ - property that a macro writes. + @ObservableViewModel requires @Observable on this class. \ + Add @Observable explicitly so it can track the state property. """, id: "missingObservable" ) @@ -54,8 +45,8 @@ public struct ObservableViewModelMacro { guard let state = declaration.property(named: "state") else { throw MacroError( """ - @ObservableViewModel needs a state property that conforms to ViewState. - Add @MainActor var state = MyState(). + @ObservableViewModel requires a state property whose type conforms to ViewState. + Declare @MainActor var state: MyState without a default value. """, id: "missingState" ) @@ -69,9 +60,8 @@ public struct ObservableViewModelMacro { id: "stateNotOnMain" ) } - // A default value on `state` makes Swift synthesize an initializer - // that is isolated to both the class actor and the main actor, which - // does not compile. The macro writes the default instead. + // A state default produces conflicting actor isolation in Swift's synthesized initializer. + // The macro supplies the default through its generated initializer instead. guard state.bindings.allSatisfy({ $0.initializer == nil }) else { throw MacroError( """ @@ -105,14 +95,14 @@ extension ObservableViewModelMacro: MemberMacro { guard declaration.declaredInitializers.isEmpty else { throw MacroError( """ - @ObservableViewModel writes the initializer, so this class \ - must not declare one. To set up state, pass it in: \ - MyViewModel(initialState: MyState(...)). + @ObservableViewModel generates the initializer. Remove the initializer from this class. \ + Pass starting state through MyViewModel(initialState: MyState(...)). """, id: "declaredInitializer" ) } + // Macro expansion cannot resolve dependency types, so generated properties use type inference. let dependencies = try dependencyNames(of: node).map { name in "private let \(raw: name) = Container.shared.\(raw: name)()" as DeclSyntax } diff --git a/Sources/ObservableViewModelMacros/Support.swift b/Sources/ObservableViewModelMacros/Support.swift index 8ba138b..aa64d37 100644 --- a/Sources/ObservableViewModelMacros/Support.swift +++ b/Sources/ObservableViewModelMacros/Support.swift @@ -1,7 +1,6 @@ import SwiftSyntax import SwiftDiagnostics -/// An error the macro reports against one piece of syntax. struct MacroError: Error, DiagnosticMessage { let message: String let diagnosticID: MessageID @@ -13,10 +12,7 @@ struct MacroError: Error, DiagnosticMessage { } } -/// Attributes that say nothing about isolation. -/// -/// Anything else on a declaration counts as a stated actor. A macro cannot -/// resolve a type, so the check reads names and nothing more. See docs/adr/0003. +// Macro expansion cannot resolve attribute types. Treat unrecognized attributes as possible global actors. private let nonIsolationAttributes: Set = [ "Observable", "ObservableViewModel", "Inject", "Sendable", "unchecked", "retroactive", "available", "objc", "objcMembers", "nonobjc", "inlinable", @@ -26,7 +22,6 @@ private let nonIsolationAttributes: Set = [ extension DeclGroupSyntax { - /// The names of every attribute on the declaration. var attributeNames: [String] { attributes.compactMap { attribute in guard case .attribute(let attribute) = attribute else { return nil } @@ -34,22 +29,18 @@ extension DeclGroupSyntax { } } - /// The first attribute that states an actor, or `nil`. var statedActor: String? { attributeNames.first { !nonIsolationAttributes.contains($0) } } - /// True when the declaration carries the named attribute. func hasAttribute(_ name: String) -> Bool { attributeNames.contains(name) } - /// Every initializer the declaration writes out. var declaredInitializers: [InitializerDeclSyntax] { memberBlock.members.compactMap { $0.decl.as(InitializerDeclSyntax.self) } } - /// The stored property with the given name, or `nil`. func property(named name: String) -> VariableDeclSyntax? { memberBlock.members .compactMap { $0.decl.as(VariableDeclSyntax.self) } @@ -63,7 +54,6 @@ extension DeclGroupSyntax { extension VariableDeclSyntax { - /// True when the property carries the named attribute. func hasAttribute(_ name: String) -> Bool { attributes.contains { attribute in guard case .attribute(let attribute) = attribute else { return false } @@ -71,10 +61,6 @@ extension VariableDeclSyntax { } } - /// The type of the property. - /// - /// It reads the annotation first. Without one, it reads the name of the - /// type the initializer calls, so `var state = SomeState()` also works. var resolvedTypeName: String? { guard let binding = bindings.first else { return nil } if let annotation = binding.typeAnnotation { diff --git a/Tests/ObservableViewModelTests/ConcurrentObservationTests.swift b/Tests/ObservableViewModelTests/ConcurrentObservationTests.swift new file mode 100644 index 0000000..67935a4 --- /dev/null +++ b/Tests/ObservableViewModelTests/ConcurrentObservationTests.swift @@ -0,0 +1,125 @@ +import FactoryKit +import FactoryTesting +import Observation +import ObservationShim +import ObservationTesting +import ObservableViewModel +import Testing + +@globalActor +private actor CounterSourceActor { + static let shared = CounterSourceActor() +} + +@CounterSourceActor +private protocol CounterSource: Sendable { + var values: ObservationsShim { get } + func set(_ value: Int) +} + +@CounterSourceActor +@Observable +private final class ObservableCounterSource: CounterSource { + private var value = 0 + + nonisolated init() {} + + var values: ObservationsShim { + ObservationsShim { self.value } + } + + func set(_ value: Int) { + self.value = value + } +} + +extension Container { + fileprivate var observationCounter: Factory { + self { ObservableCounterSource() }.cached + } +} + +private struct ObservedCounterState: ViewState { + var count = -1 +} + +@available(iOS 18.0, macOS 15.0, *) +@ViewModelActor +@Observable +@ObservableViewModel(\.observationCounter) +private final class ObservedCounterViewModel { + @MainActor var state: ObservedCounterState + + func observe() async { + let values = await observationCounter.values + await bind(values, to: \.count) + } + + func set(_ value: Int) async { + await observationCounter.set(value) + } +} + +@Suite("Concurrent observation", .container) +@MainActor +struct ConcurrentObservationTests { + @Test(arguments: [10, 20, 30]) + @available(iOS 18.0, macOS 15.0, *) + func bindsTheInitialValueFromItsOwnContainer(initialValue: Int) async throws { + let source = ObservableCounterSource() + await source.set(initialValue) + Container.shared.observationCounter.register { source } + let viewModel = ObservedCounterViewModel() + let observation = Task { await viewModel.observe() } + defer { observation.cancel() } + + try await ObservationsShim { viewModel.state.count } + .fulfillment(of: initialValue, timeout: .seconds(2)) + + #expect(viewModel.state.count == initialValue) + observation.cancel() + await observation.value + } + + @Test(arguments: [100, 200, 300]) + @available(iOS 18.0, macOS 15.0, *) + func bindsAnActionFromItsOwnContainer(updatedValue: Int) async throws { + let source = ObservableCounterSource() + Container.shared.observationCounter.register { source } + let viewModel = ObservedCounterViewModel() + let observation = Task { await viewModel.observe() } + defer { observation.cancel() } + let counts = ObservationsShim { viewModel.state.count } + + try await counts.fulfillment(of: 0, timeout: .seconds(2)) + try await counts.fulfillment(of: updatedValue, timeout: .seconds(2)) { + await viewModel.set(updatedValue) + } + + #expect(viewModel.state.count == updatedValue) + observation.cancel() + await observation.value + } + + @Test + @available(iOS 18.0, macOS 15.0, *) + func cancellationStopsStateUpdatesWhileTheSourceRemainsActive() async throws { + let source = ObservableCounterSource() + Container.shared.observationCounter.register { source } + let viewModel = ObservedCounterViewModel() + let observation = Task { await viewModel.observe() } + defer { observation.cancel() } + + try await ObservationsShim { viewModel.state.count } + .fulfillment(of: 0, timeout: .seconds(2)) + observation.cancel() + await observation.value + + let values = await source.values + try await values.fulfillment(of: 99, timeout: .seconds(2)) { + await viewModel.set(99) + } + + #expect(viewModel.state.count == 0) + } +} diff --git a/Tests/ObservableViewModelTests/ObservableViewModelTests.swift b/Tests/ObservableViewModelTests/ObservableViewModelTests.swift index b693ded..14bc054 100644 --- a/Tests/ObservableViewModelTests/ObservableViewModelTests.swift +++ b/Tests/ObservableViewModelTests/ObservableViewModelTests.swift @@ -23,7 +23,6 @@ final class Greeter: Greeting { func callAsFunction() -> String { "hello" } } -// Registration is plain Factory. See docs/adr/0005. extension Container { var greeter: Factory { self { Greeter() }.scope(.cached) } } @@ -65,8 +64,7 @@ func initialStateCanBeSuppliedByTheView() async throws { func theProtocolRegistrationLetsATestSwapTheDependency() async throws { @DomainActor final class Quiet: Greeting { func callAsFunction() -> String { "shh" } } Container.shared.greeter.register { Quiet() } - // `.all` clears the scope cache too. A plain reset leaves the cached - // mock in place for the next test. + // Use `.all` to clear cached mocks as well as registrations. defer { Container.shared.greeter.reset(.all) } let viewModel = CounterViewModel() diff --git a/Tests/ObservableViewModelTests/SubscriptionTests.swift b/Tests/ObservableViewModelTests/SubscriptionTests.swift index 28ddbd0..853f8f7 100644 --- a/Tests/ObservableViewModelTests/SubscriptionTests.swift +++ b/Tests/ObservableViewModelTests/SubscriptionTests.swift @@ -53,7 +53,7 @@ final class Source { var value = 1 } -/// Waits until the condition is true, or gives up after many turns. +/// Yields up to 10,000 times while the condition is false. Does not report a failure on exhaustion. @MainActor func waitUntil(_ condition: () -> Bool) async { for _ in 0 ..< 10_000 { @@ -83,7 +83,6 @@ struct ObserveTests { @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()