Skip to content

Commit

Permalink
Added Array element listener
Browse files Browse the repository at this point in the history
  • Loading branch information
ddaddy committed Sep 20, 2023
1 parent 37f0006 commit ff5a252
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ Example:
.uniques(by: \.firstName, and: \.surname)
```

Adds a listener to array elements

```swift
elementChangeListener(cancellables: inout [AnyCancellable], change: @escaping (Element)->())
```

### CLLocationCoordinate2D
Determine if a location is within a bounding rect

Expand Down
36 changes: 36 additions & 0 deletions Sources/Common/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,39 @@ extension Array {
}
}
}

#if canImport(Combine)
import Combine

@available(iOS 13.0, watchOS 6.0, macOS 10.15, *)
public
extension Array where Element: ObservableObject {

/// Adds a listener to array elements
/// - Parameters:
/// - cancellables: An `Array` of `AnyCancellable`'s to hold the strong reference to listeners
/// - change: A closure that is triggered whenever an element in the array has been updated by firing `objectWillChange`
///
/// As arrays containing class objects do not trigger any kind of update if an element
/// updates one of it's variables, we need to attach a listener to every element of the array.
/// The listener needs a strong reference, so you must pass in an array to hold them.
///
/// Example:
/// ```swift
/// var cancellables = [AnyCancellable]()
/// array.elementChangeListener(cancellables: &cancellables) { element in
/// // Do something when an array element changes
/// }
/// ```
func elementChangeListener(cancellables: inout [AnyCancellable], change: @escaping (Element)->()) {

cancellables.removeAll()
forEach { element in
let c = element.objectWillChange.sink { _ in
change(element)
}
cancellables.append(c)
}
}
}
#endif

0 comments on commit ff5a252

Please sign in to comment.