Skip to content

Commit

Permalink
Merge pull request #75 from unsignedapps/user-defaults-filtering
Browse files Browse the repository at this point in the history
Filter `UserDefaults` so only the subscribed instance emits
  • Loading branch information
bok- authored Mar 19, 2021
2 parents 6380151 + 48c5d8e commit fb58548
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Sources/Vexil/Sources/UserDefaults+FlagValueSource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ extension UserDefaults: FlagValueSource {
/// A Publisher that emits events when the flag values it manages changes
public var valuesDidChange: AnyPublisher<Void, Never>? {
return NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)
.filter { ($0.object as AnyObject) === self }
.map { _ in () }
.eraseToAnyPublisher()
}
Expand All @@ -55,7 +56,9 @@ extension UserDefaults: FlagValueSource {

public var valuesDidChange: AnyPublisher<Void, Never>? {
return Publishers.Merge (
NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification).map { _ in () },
NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)
.filter { ($0.object as AnyObject) === self }
.map { _ in () },
NotificationCenter.default.publisher(for: ApplicationDidBecomeActive).map { _ in () }
)
.eraseToAnyPublisher()
Expand Down
27 changes: 27 additions & 0 deletions Tests/VexilTests/UserDefaultPublisherTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,33 @@ final class UserDefaultPublisherTests: XCTestCase {
XCTAssertEqual(snapshots.count, 2)
}

func testDoesNotPublishWhenDifferentUserDefaultsChange () {
let expectation = self.expectation(description: "published")

let defaults1 = UserDefaults(suiteName: "Test Suite")!
let defaults2 = UserDefaults(suiteName: "Separate Test Suite")!
let pole = FlagPole(hoist: TestFlags.self, sources: [ defaults1 ])

var snapshots = [Snapshot<TestFlags>]()

let cancellable = pole.publisher
.dropFirst() // drop the immediate publish upon subscribing
.sink { snapshot in
snapshots.append(snapshot)
if snapshots.count == 1 {
expectation.fulfill()
}
}

defaults2.set("Test Value", forKey: "test-key")
defaults1.set(123, forKey: "second-test-key")

self.wait(for: [ expectation ], timeout: 1)

XCTAssertNotNil(cancellable)
XCTAssertEqual(snapshots.count, 1)
}

}


Expand Down

0 comments on commit fb58548

Please sign in to comment.