File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -86,6 +86,12 @@ Example:
86
86
.uniques (by : \.firstName , and : \.surname )
87
87
```
88
88
89
+ Adds a listener to array elements
90
+
91
+ ``` swift
92
+ elementChangeListener (cancellables : inout [AnyCancellable], change : @escaping (Element )-> ())
93
+ ```
94
+
89
95
### CLLocationCoordinate2D
90
96
Determine if a location is within a bounding rect
91
97
Original file line number Diff line number Diff line change @@ -136,3 +136,39 @@ extension Array {
136
136
}
137
137
}
138
138
}
139
+
140
+ #if canImport(Combine)
141
+ import Combine
142
+
143
+ @available ( iOS 13 . 0 , watchOS 6 . 0 , macOS 10 . 15 , * )
144
+ public
145
+ extension Array where Element: ObservableObject {
146
+
147
+ /// Adds a listener to array elements
148
+ /// - Parameters:
149
+ /// - cancellables: An `Array` of `AnyCancellable`'s to hold the strong reference to listeners
150
+ /// - change: A closure that is triggered whenever an element in the array has been updated by firing `objectWillChange`
151
+ ///
152
+ /// As arrays containing class objects do not trigger any kind of update if an element
153
+ /// updates one of it's variables, we need to attach a listener to every element of the array.
154
+ /// The listener needs a strong reference, so you must pass in an array to hold them.
155
+ ///
156
+ /// Example:
157
+ /// ```swift
158
+ /// var cancellables = [AnyCancellable]()
159
+ /// array.elementChangeListener(cancellables: &cancellables) { element in
160
+ /// // Do something when an array element changes
161
+ /// }
162
+ /// ```
163
+ func elementChangeListener( cancellables: inout [ AnyCancellable ] , change: @escaping ( Element ) -> ( ) ) {
164
+
165
+ cancellables. removeAll ( )
166
+ forEach { element in
167
+ let c = element. objectWillChange. sink { _ in
168
+ change ( element)
169
+ }
170
+ cancellables. append ( c)
171
+ }
172
+ }
173
+ }
174
+ #endif
You can’t perform that action at this time.
0 commit comments