|
| 1 | +/// MIT License |
| 2 | +/// |
| 3 | +/// Copyright (c) 2022 Point-Free, Inc. |
| 4 | +/// |
| 5 | +/// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +/// of this software and associated documentation files (the "Software"), to deal |
| 7 | +/// in the Software without restriction, including without limitation the rights |
| 8 | +/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +/// copies of the Software, and to permit persons to whom the Software is |
| 10 | +/// furnished to do so, subject to the following conditions: |
| 11 | +/// |
| 12 | +/// The above copyright notice and this permission notice shall be included in all |
| 13 | +/// copies or substantial portions of the Software. |
| 14 | +/// |
| 15 | +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +/// SOFTWARE. |
| 22 | + |
| 23 | +/// A generic wrapper for isolating a mutable value to an actor. |
| 24 | +/// |
| 25 | +/// This type is most useful when writing tests for when you want to inspect what happens inside an |
| 26 | +/// effect. For example, suppose you have a feature such that when a button is tapped you track some |
| 27 | +/// analytics: |
| 28 | +/// |
| 29 | +/// ```swift |
| 30 | +/// class FeatureModel: ObservableObject { |
| 31 | +/// @Dependency(\.analytics) var analytics |
| 32 | +/// // ... |
| 33 | +/// func buttonTapped() { |
| 34 | +/// // ... |
| 35 | +/// await self.analytics.track("Button tapped") |
| 36 | +/// } |
| 37 | +/// } |
| 38 | +/// ``` |
| 39 | +/// |
| 40 | +/// Then, in tests we can construct an analytics client that appends events to a mutable array |
| 41 | +/// rather than actually sending events to an analytics server. However, in order to do this in a |
| 42 | +/// safe way we should use an actor, and `ActorIsolated` makes this easy: |
| 43 | +/// |
| 44 | +/// ```swift |
| 45 | +/// func testAnalytics() async { |
| 46 | +/// let events = ActorIsolated<[String]>([]) |
| 47 | +/// let model = withDependencies { |
| 48 | +/// $0.analytics = AnalyticsClient( |
| 49 | +/// track: { event in await events.withValue { $0.append(event) } } |
| 50 | +/// ) |
| 51 | +/// } operation: { |
| 52 | +/// FeatureModel() |
| 53 | +/// } |
| 54 | +/// |
| 55 | +/// model.buttonTapped() |
| 56 | +/// await events.withValue { |
| 57 | +/// XCTAssertEqual($0, ["Button tapped"]) |
| 58 | +/// } |
| 59 | +/// } |
| 60 | +/// ``` |
| 61 | +/// |
| 62 | +/// To synchronously isolate a value, see ``LockIsolated``. |
| 63 | +@dynamicMemberLookup |
| 64 | +final actor ActorIsolated<Value> { |
| 65 | + /// The actor-isolated value. |
| 66 | + var value: Value |
| 67 | + |
| 68 | + /// Initializes actor-isolated state around a value. |
| 69 | + /// |
| 70 | + /// - Parameter value: A value to isolate in an actor. |
| 71 | + init(_ value: @autoclosure @Sendable () throws -> Value) rethrows { |
| 72 | + self.value = try value() |
| 73 | + } |
| 74 | + |
| 75 | + subscript<Subject>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject { |
| 76 | + self.value[keyPath: keyPath] |
| 77 | + } |
| 78 | + |
| 79 | + /// Perform an operation with isolated access to the underlying value. |
| 80 | + /// |
| 81 | + /// Useful for modifying a value in a single transaction. |
| 82 | + /// |
| 83 | + /// ```swift |
| 84 | + /// // Isolate an integer for concurrent read/write access: |
| 85 | + /// let count = ActorIsolated(0) |
| 86 | + /// |
| 87 | + /// func increment() async { |
| 88 | + /// // Safely increment it: |
| 89 | + /// await self.count.withValue { $0 += 1 } |
| 90 | + /// } |
| 91 | + /// ``` |
| 92 | + /// |
| 93 | + /// > Tip: Because XCTest assertions don't play nicely with Swift concurrency, `withValue` also |
| 94 | + /// > provides a handy interface to peek at an actor-isolated value and assert against it: |
| 95 | + /// > |
| 96 | + /// > ```swift |
| 97 | + /// > let didOpenSettings = ActorIsolated(false) |
| 98 | + /// > let model = withDependencies { |
| 99 | + /// > $0.openSettings = { await didOpenSettings.setValue(true) } |
| 100 | + /// > } operation: { |
| 101 | + /// > FeatureModel() |
| 102 | + /// > } |
| 103 | + /// > await model.settingsButtonTapped() |
| 104 | + /// > await didOpenSettings.withValue { XCTAssertTrue($0) } |
| 105 | + /// > ``` |
| 106 | + /// |
| 107 | + /// - Parameters: operation: An operation to be performed on the actor with the underlying value. |
| 108 | + /// - Returns: The result of the operation. |
| 109 | + func withValue<T>( |
| 110 | + _ operation: @Sendable (inout Value) throws -> T |
| 111 | + ) rethrows -> T { |
| 112 | + var value = self.value |
| 113 | + defer { self.value = value } |
| 114 | + return try operation(&value) |
| 115 | + } |
| 116 | + |
| 117 | + /// Overwrite the isolated value with a new value. |
| 118 | + /// |
| 119 | + /// ```swift |
| 120 | + /// // Isolate an integer for concurrent read/write access: |
| 121 | + /// let count = ActorIsolated(0) |
| 122 | + /// |
| 123 | + /// func reset() async { |
| 124 | + /// // Reset it: |
| 125 | + /// await self.count.setValue(0) |
| 126 | + /// } |
| 127 | + /// ``` |
| 128 | + /// |
| 129 | + /// > Tip: Use ``withValue(_:)-805p`` instead of `setValue` if the value being set is derived from |
| 130 | + /// > the current value. This isolates the entire transaction and avoids data races between |
| 131 | + /// > reading and writing the value. |
| 132 | + /// |
| 133 | + /// - Parameter newValue: The value to replace the current isolated value with. |
| 134 | + func setValue(_ newValue: @autoclosure @Sendable () throws -> Value) rethrows { |
| 135 | + self.value = try newValue() |
| 136 | + } |
| 137 | +} |
0 commit comments