Why is the SwiftUI re-render the UI event if the view does not use the counter like in the example bellow...shouldn't SwiftUI framework be smart enough to detect that??
import SwiftUI
class ViewModel: ObservableObject {
@Published var counter: Int = 0 // Not used in the view's body
@Published var displayText: String = "Hello" // Used in the view's body
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
VStack {
Text(viewModel.displayText) // Depends on displayText
}
.onChange(of: viewModel.counter) { newValue in
print("Counter changed to: \(newValue)")
}
}
}
Is there any solution more elegant without using Publishers??
Line 4: @Published var counter: Int = 0 // Not used in the view's body
Line 15 (inside the view's body): .onChange(of: viewModel.counter) { newValue in
Sorry, but counter
is used in the view's body.
Just make it not a @Published
var and it probably won't do what you claim it's doing.