Skip to content

Commit c838d36

Browse files
authored
Fix bug that KeepAlive is not effective (#51)
1 parent bab0635 commit c838d36

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Sources/Atoms/Core/StoreContext.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ private extension StoreContext {
424424
// 1. It's not marked as `KeepAlive`.
425425
// 2. It has no downstream atoms.
426426
// 3. It has no subscriptions from views.
427-
let shouldKeepAlive = store.state.caches[key].map { $0 is any KeepAlive } ?? false
427+
let shouldKeepAlive = store.state.caches[key].map { $0.atom is any KeepAlive } ?? false
428428
let isChildrenEmpty = store.graph.children[key]?.isEmpty ?? true
429429
let isSubscriptionEmpty = store.state.subscriptions[key]?.isEmpty ?? true
430430
let shouldRelease = !shouldKeepAlive && isChildrenEmpty && isSubscriptionEmpty

Tests/AtomsTests/Core/StoreContextTests.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,44 @@ final class StoreContextTests: XCTestCase {
286286
XCTAssertTrue(state?.coordinator === newState?.coordinator)
287287
}
288288

289+
func testRelease() {
290+
struct KeepAliveAtom<T: Hashable>: ValueAtom, KeepAlive, Hashable {
291+
var value: T
292+
293+
func value(context: Context) -> T {
294+
value
295+
}
296+
}
297+
298+
let store = AtomStore()
299+
let context = StoreContext(store)
300+
301+
XCTContext.runActivity(named: "Normal atoms should be released.") { _ in
302+
let atom = TestAtom(value: 0)
303+
let key = AtomKey(atom)
304+
let transaction = Transaction(key: key) {}
305+
306+
_ = context.watch(atom, in: transaction)
307+
XCTAssertNotNil(store.state.caches[key])
308+
309+
context.reset(atom)
310+
XCTAssertNil(store.state.caches[key])
311+
}
312+
313+
XCTContext.runActivity(named: "KeepAlive atoms should not be released.") { _ in
314+
let atom = KeepAliveAtom(value: 0)
315+
let key = AtomKey(atom)
316+
let transaction = Transaction(key: key) {}
317+
318+
_ = context.watch(atom, in: transaction)
319+
320+
XCTAssertNotNil(store.state.caches[key])
321+
322+
context.reset(atom)
323+
XCTAssertNotNil(store.state.caches[key])
324+
}
325+
}
326+
289327
func testObservers() {
290328
let store = AtomStore()
291329
let container = SubscriptionContainer()

0 commit comments

Comments
 (0)