Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,27 @@ public struct ObservationRegistrar: Sendable {
}
}

internal mutating func cancelAll() {
internal mutating func deinitialize() -> (@Sendable () -> Void)? {
func extractSelf<T>(_ ty: T.Type) -> AnyKeyPath {
return \T.self
}

var tracker: (@Sendable () -> Void)?
lookupIteration: for (keyPath, ids) in lookups {
for id in ids {
if let found = observations[id]?.willSetTracker {
// convert the keyPath into its \Self.self version
let selfKp = _openExistential(type(of: keyPath).rootType, do: extractSelf)
tracker = {
found(selfKp)
}
break lookupIteration
}
}
}
observations.removeAll()
lookups.removeAll()
return tracker
}

internal mutating func willSet(keyPath: AnyKeyPath) -> [@Sendable (AnyKeyPath) -> Void] {
Expand Down Expand Up @@ -157,8 +175,8 @@ public struct ObservationRegistrar: Sendable {
state.withCriticalRegion { $0.cancel(id) }
}

internal func cancelAll() {
state.withCriticalRegion { $0.cancelAll() }
internal func deinitialize() {
state.withCriticalRegion { $0.deinitialize() }?()
}

internal func willSet<Subject: Observable, Member>(
Expand Down Expand Up @@ -189,7 +207,7 @@ public struct ObservationRegistrar: Sendable {
}

deinit {
context.cancelAll()
context.deinitialize()
}
}

Expand Down
33 changes: 33 additions & 0 deletions test/stdlib/Observation/Observable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,22 @@ final class CowTest {
var container = CowContainer()
}

@Observable
final class DeinitTriggeredObserver {
var property: Int = 3
var property2: Int = 4
let deinitTrigger: () -> Void

init(_ deinitTrigger: @escaping () -> Void) {
self.deinitTrigger = deinitTrigger
}

deinit {
deinitTrigger()
}
}


@main
struct Validator {
@MainActor
Expand Down Expand Up @@ -511,6 +527,23 @@ struct Validator {
expectEqual(subject.container.id, startId)
}

suite.test("weak container observation") {
let changed = CapturedState(state: false)
let deinitialized = CapturedState(state: 0)
var test = DeinitTriggeredObserver {
deinitialized.state += 1
}
withObservationTracking { [weak test] in
_blackHole(test?.property)
_blackHole(test?.property2)
} onChange: {
changed.state = true
}
test = DeinitTriggeredObserver { }
expectEqual(deinitialized.state, 1) // ensure only one invocation is done per deinitialization
expectEqual(changed.state, true)
}

runAllTests()
}
}
Expand Down