I have tried to modify ColorCalc in chapter 19 to use @Observable for the CalculatorViewModel. There were several issues which I could not solve.
- Can no longer use @Published for properties.
- Cannot create publishers on properties by adding $
- Tried to use various solutions suggested, eg in stack overflow
// See: swift - How to get a publisher from a value, since the beauty of @Observable? - Stack Overflow
@Observable
class Fool {
var cancellables = Set()
var isEnabled: Bool = false { didSet { isEnabled$ = isEnabled } }
@ObservationIgnored
@Published var isEnabled$: Bool = false
init() {
$isEnabled$
.removeDuplicates() // Prevent infinite loop
.sink { self.isEnabled = $0; print($0) }
.store(in: &cancellables)
}
}
However the above does not work in CalculatorViewModel, since in @Observables βdidSetβ is no longer called, though there is a complex solution apparently using withObservationTracking (eg see: Cancellable withObservationTracking in Swift β Augmented Code) which I could not get to work (newbie).
-
It seems easier to just implement computed variables for all model properties that depend upon hexText, eg
var color: Color {
if let c = Color.redGreenBlueOpacity(forHex: hexText) {
return Color(values: c)
}
return .white
}
var rgboText: String {
if let values = Color.redGreenBlueOpacity(forHex: hexText) {
return [values.0, values.1, values.2, values.3]
.map { String(describing: Int($0 * 255)) }
.joined(separator: ", ")
}
return ββ, β, β, ββ
}
var name: String {
let name = ColorName(hex: hexText)
if let name {
return β(name) (Color.opacityString(forHex: hexText))β
} else {
return β------------β
}
} -
So my main question is, do I have to continue to use ObservableObject with @Published rather than move to the βmodernβ @Observable. Apple have stated we can just swap this for our ObservableObjects and it all should just work, but it doesnβt with Combine (as far as I can tell).
Thoughts from the experts please?