Add Injected property wrapper with reactive DI observer cleanup
This commit is contained in:
parent
be7931b062
commit
86940f3d7d
1 changed files with 32 additions and 0 deletions
32
Sources/LuminateDI/Injected.swift
Normal file
32
Sources/LuminateDI/Injected.swift
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import Adwaita
|
||||
import Foundation
|
||||
|
||||
@propertyWrapper
|
||||
public struct Injected<T> {
|
||||
|
||||
private let keyPath: KeyPath<InjectionValues, T?>
|
||||
private let observerRef: ObserverRef
|
||||
|
||||
public var wrappedValue: T {
|
||||
DIContainer.shared.resolve(keyPath)
|
||||
}
|
||||
|
||||
public init(_ keyPath: KeyPath<InjectionValues, T?>) {
|
||||
self.keyPath = keyPath
|
||||
self.observerRef = ObserverRef()
|
||||
observerRef.id = DIContainer.shared.addObserver(for: keyPath) {
|
||||
Task { @MainActor in
|
||||
StateManager.updateViews()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class ObserverRef {
|
||||
var id: UUID?
|
||||
deinit {
|
||||
if let id {
|
||||
DIContainer.shared.removeObserver(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue