simplifications to ReactiveFormModel
gorgatron1 opened this issue · comments
Hi,
I noticed that you are using explicit publishers plus didSet
in https://github.com/heckj/swiftui-notes/blob/master/SwiftUI-Notes/ReactiveFormModel.swift
An @Published
property wrapper actually includes a publisher that publishes changes and you can get to it with $property
(except of course in init!).
Anyway you could change your code like this:
class ReactiveFormModel : ObservableObject {
@Published var firstEntry: String = ""
@Published var secondEntry: String = ""
init() {
// would like to use $firstEntry, but that is not available in init
let validationPipeline = Publishers.CombineLatest(_firstEntry.projectedValue, _secondEntry.projectedValue)
As long as you didn't need particular semantics of CurrentValueSubject
You're absolutely right, and it would be smaller code and fewer moving parts, but from a descriptive "this is how it's working" point of view, I think it would also be harder to explain. All of sudden you've got this whole _firstEntry
thing that isn't otherwise obvious as a side effect of @Published
property value as well as the .projectedValue
. It's tighter code, but I thought the explicitness of the semantics behind { didSet }
was easier to visually grok while reading the code.
The heart of this example isn't how property wrappers do their magic, but how CombineLatest can bring the values together and then allow you to declaratively use the results of that to update the UI appropriately for your use case.
Cool! It might be worth a comment then that some of this can be wrapped up inside. It is a nice example, but people might copy it too slavishly and not realize :-)
Thanks for reading!