Skip to content

Commit

Permalink
Merge pull request #285 from n3d1117/fix/published-property-fix
Browse files Browse the repository at this point in the history
Simplify @published implementation using Property
  • Loading branch information
srdanrasic authored Nov 22, 2024
2 parents 57a902a + 5b0360c commit 35ac6f9
Showing 1 changed file with 9 additions and 19 deletions.
28 changes: 9 additions & 19 deletions Sources/Published.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,49 +11,39 @@
@propertyWrapper
public struct Published<Value> {

private var value: Value
private var publisher: Publisher?
private let publisher: Publisher
private let willChangeSubject = PassthroughSubject<Void, Never>()

public init(wrappedValue: Value) {
value = wrappedValue
publisher = Publisher(wrappedValue)
}

/// A publisher for properties used with the `@Published` attribute.
public struct Publisher: SignalProtocol {
public typealias Element = Value
public typealias Error = Never

fileprivate let didChangeSubject: ReplayOneSubject<Value, Never>
fileprivate let property: Property<Value>

public func observe(with observer: @escaping (Signal<Value, Never>.Event) -> Void) -> Disposable {
self.didChangeSubject.observe(with: observer)
self.property.observe(with: observer)
}

fileprivate init(_ output: Element) {
self.didChangeSubject = ReplayOneSubject()
self.didChangeSubject.send(output)
self.property = Property(output)
}
}

public var wrappedValue: Value {
get { self.value }
set {
get { self.publisher.property.value }
nonmutating set {
self.willChangeSubject.send()
self.value = newValue
self.publisher?.didChangeSubject.send(newValue)
self.publisher.property.value = newValue
}
}

public var projectedValue: Publisher {
mutating get {
if let publisher = publisher {
return publisher
}
let publisher = Publisher(value)
self.publisher = publisher
return publisher
}
get { publisher }
}
}

Expand Down

0 comments on commit 35ac6f9

Please sign in to comment.