Skip to content

Commit 2c41085

Browse files
authored
Set up dispatch sources after external write. (#148)
* Set up dispatch sources after external write. * fix * fix
1 parent 6dbf8cb commit 2c41085

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

Sources/Sharing/SharedKeys/FileStorageKey.swift

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -150,11 +150,7 @@
150150
[weak self] in
151151
guard let self else { return }
152152
let fileExists = self.storage.fileExists(self.url)
153-
defer {
154-
if !fileExists {
155-
setUpSources()
156-
}
157-
}
153+
defer { setUpSources() }
158154
let modificationDate =
159155
fileExists
160156
? (try? self.storage.attributesOfItemAtPath(self.url.path)[.modificationDate]

Tests/SharingTests/FileStorageTests.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,50 @@
421421
#expect(count == 1)
422422
#expect(try String(decoding: Data(contentsOf: .fileURL), as: UTF8.self) == "1")
423423
}
424+
425+
@Test func twoShareds() async throws {
426+
let count1URL = URL(fileURLWithPath: NSTemporaryDirectory())
427+
.appendingPathComponent("file.json")
428+
let count2URL = URL(fileURLWithPath: NSTemporaryDirectory() + "/")
429+
.appendingPathComponent("file.json")
430+
try? FileManager.default.removeItem(at: count1URL)
431+
try? FileManager.default.removeItem(at: count2URL)
432+
433+
@Shared(.fileStorage(count1URL)) var count1 = 0
434+
@Shared(.fileStorage(count2URL)) var count2 = 0
435+
436+
$count1.withLock { $0 = 42 }
437+
#expect(count1 == 42)
438+
try await Task.sleep(for: .seconds(1.5))
439+
#expect(count2 == 42)
440+
441+
$count2.withLock { $0 = 1728 }
442+
#expect(count2 == 1728)
443+
try await Task.sleep(for: .seconds(1.5))
444+
#expect(count1 == 1728)
445+
446+
$count1.withLock { $0 = 999 }
447+
#expect(count1 == 999)
448+
try await Task.sleep(for: .seconds(1.5))
449+
#expect(count2 == 999)
450+
}
451+
452+
@Test func externalAtomicWrite() async throws {
453+
@Shared(.fileStorage(.fileURL)) var count = 0
454+
455+
try Data("42".utf8).write(to: .fileURL, options: .atomic)
456+
try await Task.sleep(for: .seconds(1.5))
457+
#expect(count == 42)
458+
459+
try Data("1728".utf8).write(to: .fileURL, options: .atomic)
460+
try await Task.sleep(for: .seconds(1.5))
461+
#expect(count == 1728)
462+
463+
$count.withLock { $0 = 999 }
464+
try await Task.sleep(for: .seconds(1.5))
465+
#expect(count == 999)
466+
#expect(try String(decoding: Data(contentsOf: .fileURL), as: UTF8.self) == "999")
467+
}
424468
}
425469
}
426470

0 commit comments

Comments
 (0)