@@ -59,23 +59,30 @@ public final class FlagPole<RootGroup>: Sendable where RootGroup: FlagContainer
5959 // MARK: - Sources
6060
6161 /// An Array of `FlagValueSource`s that are used during flag value lookup.
62- ///
63- /// This array is mutable so you can manipulate it directly whenever your
64- /// need to change the hierarchy of your flag sources.
65- ///
6662 /// The order of this Array is the order used when looking up flag values.
6763 ///
64+ /// To update the list of sources use ``
65+ ///
6866 public var _sources : [ any FlagValueSource ] {
69- get {
70- manager. withLockUnchecked {
71- $0. sources
72- }
67+ manager. withLockUnchecked {
68+ $0. sources
7369 }
74- set {
75- manager. withLockUnchecked { manager in
76- let oldValue = manager. sources
77- manager. sources = newValue
78- subscribeChannel ( oldSources: oldValue, newSources: newValue, on: & manager)
70+ }
71+
72+ /// Updates the list of `FlagValueSource`s using the supplied closure.
73+ ///
74+ /// - Parameters:
75+ /// - closure: A closure that is passed a mutable copy of the sources array.
76+ ///
77+ public func updateSources( _ closure: ( inout [ any FlagValueSource ] ) throws -> Void ) rethrows {
78+ try manager. withLockUnchecked { manager in
79+ let oldValue = manager. sources
80+ var copy = manager. sources
81+ try closure ( & copy)
82+ manager. sources = copy
83+
84+ if oldValue. map ( \. flagValueSourceID) != copy. map ( \. flagValueSourceID) {
85+ subscribeChannel ( oldSources: oldValue, newSources: copy, on: & manager)
7986 }
8087 }
8188 }
@@ -312,7 +319,9 @@ public final class FlagPole<RootGroup>: Sendable where RootGroup: FlagContainer
312319 /// - at: The index at which to insert the `Snapshot`.
313320 ///
314321 public func insert( snapshot: Snapshot < RootGroup > , at index: Array < any FlagValueSource > . Index ) {
315- _sources. insert ( snapshot, at: index)
322+ updateSources {
323+ $0. insert ( snapshot, at: index)
324+ }
316325 }
317326
318327 /// Appends a `Snapshot` to the end of the `FlagPole`s source hierarchy.
@@ -323,7 +332,9 @@ public final class FlagPole<RootGroup>: Sendable where RootGroup: FlagContainer
323332 /// - snapshot: The `Snapshot` to be added to the source hierarchy.
324333 ///
325334 public func append( snapshot: Snapshot < RootGroup > ) {
326- _sources. append ( snapshot)
335+ updateSources {
336+ $0. append ( snapshot)
337+ }
327338 }
328339
329340 /// Removes a `Snapshot` from the `FlagPole`s source hierarchy.
@@ -334,7 +345,9 @@ public final class FlagPole<RootGroup>: Sendable where RootGroup: FlagContainer
334345 /// - snapshot: The `Snapshot` to be removed from the source hierarchy.
335346 ///
336347 public func remove( snapshot: Snapshot < RootGroup > ) {
337- _sources. removeAll ( where: { ( $0 as? Snapshot < RootGroup > ) ? . id == snapshot. id } )
348+ updateSources {
349+ $0. removeAll ( where: { ( $0 as? Snapshot < RootGroup > ) ? . id == snapshot. id } )
350+ }
338351 }
339352
340353
0 commit comments