Skip to content

Commit 35ac6f9

Browse files
authored
Merge pull request #285 from n3d1117/fix/published-property-fix
Simplify @published implementation using Property
2 parents 57a902a + 5b0360c commit 35ac6f9

File tree

1 file changed

+9
-19
lines changed

1 file changed

+9
-19
lines changed

Sources/Published.swift

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,49 +11,39 @@
1111
@propertyWrapper
1212
public struct Published<Value> {
1313

14-
private var value: Value
15-
private var publisher: Publisher?
14+
private let publisher: Publisher
1615
private let willChangeSubject = PassthroughSubject<Void, Never>()
1716

1817
public init(wrappedValue: Value) {
19-
value = wrappedValue
18+
publisher = Publisher(wrappedValue)
2019
}
2120

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

27-
fileprivate let didChangeSubject: ReplayOneSubject<Value, Never>
26+
fileprivate let property: Property<Value>
2827

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

3332
fileprivate init(_ output: Element) {
34-
self.didChangeSubject = ReplayOneSubject()
35-
self.didChangeSubject.send(output)
33+
self.property = Property(output)
3634
}
3735
}
3836

3937
public var wrappedValue: Value {
40-
get { self.value }
41-
set {
38+
get { self.publisher.property.value }
39+
nonmutating set {
4240
self.willChangeSubject.send()
43-
self.value = newValue
44-
self.publisher?.didChangeSubject.send(newValue)
41+
self.publisher.property.value = newValue
4542
}
4643
}
4744

4845
public var projectedValue: Publisher {
49-
mutating get {
50-
if let publisher = publisher {
51-
return publisher
52-
}
53-
let publisher = Publisher(value)
54-
self.publisher = publisher
55-
return publisher
56-
}
46+
get { publisher }
5747
}
5848
}
5949

0 commit comments

Comments
 (0)