Skip to content

Commit ff5a252

Browse files
committed
Added Array element listener
1 parent 37f0006 commit ff5a252

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ Example:
8686
.uniques(by: \.firstName, and: \.surname)
8787
```
8888

89+
Adds a listener to array elements
90+
91+
```swift
92+
elementChangeListener(cancellables: inout [AnyCancellable], change: @escaping (Element)->())
93+
```
94+
8995
### CLLocationCoordinate2D
9096
Determine if a location is within a bounding rect
9197

Sources/Common/Array.swift

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,39 @@ extension Array {
136136
}
137137
}
138138
}
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

0 commit comments

Comments
 (0)