I have been searching about how SwiftUI redraws views when property values are changed. However, I could not find a good resource that explains how this happens.
Let’s say I have a view model and two Published properties. After a method is called, two properties are updated one after each other. Theoretically, each one triggers objectWillChange
and SwiftUI redraws the view with the new data. The question is; does SwiftUI draw the view twice or once? I would say it happens once and can also observe this by debugging with Self._printChanges()
function. However, I could not find any source that explains this behavior.
Is there any resource that explains how SwiftUI handles view updates after the properties are changed?
An example;
class ExampleViewModel: ObservableObject {
@Published var loading: Bool = true
@Published var data: String = ""
func load() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: { [weak self] in
self?.data = "Data is loaded"
self?.loading = false
})
}
}
struct ExampleView: View {
@ObservedObject var viewModel: ExampleViewModel
var body: some View {
ZStack {
Text(viewModel.data)
if viewModel.loading {
LoadingView()
}
}
.task {
viewModel.load()
}
}
}