I'm observe a property on a view using the onChange
modifier. However, I'd also like the same piece of code to run on the initial value as well because sometimes the data is injected in the initializer or asynchronously loaded later.
For example, I have a view that gets a model injected. Sometimes this model has data in it to begin with (like previews), or is asynchronously retrieved from the network.
class MyModel: ObservableObject {
@Published var counter = 0
}
struct ContentView: View {
@ObservedObject var model: MyModel
var body: some View {
VStack {
Text("Counter: (model.counter)")
Button("Increment") { model.counter += 1 }
}
.onChange(of: model.counter, perform: someLogic)
.onAppear { someLogic(counter: model.counter) }
}
private func someLogic(counter: Int) {
print("onAppear: (counter)")
}
}
In both onAppear
and onChange
cases, I'd like to run someLogic(counter:)
. Is there a better way to get this behaviour or combine them?