Skip to content

Commit

Permalink
Simplify @published implementation using Property
Browse files Browse the repository at this point in the history
  • Loading branch information
n3d1117 committed Nov 21, 2024
1 parent 57a902a commit 5b0360c
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 5b0360c

Please sign in to comment.