My question is a conceptual question.
I have the following code:
struct CategoriesList : View {
@State pri
You could take a look at my answer here.
Basically you create a model object conforming to BindableObject
:
class LoginModel : BindableObject {
var didChange = PassthroughSubject()
private(set) var username: String? {
didSet {
didChange.send(self)
}
}
func load() {
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.username = "Sorin"
}
}
}
This example simulates an async server call by using the plain ol' asyncAfter
.
Then, the View links with it and it's automatically updated when the model changes.
public struct LoginScreen: View {
@ObjectBinding var loginObject = LoginModel()
public var body: some View {
Group {
if login.username == nil {
Text("Trying to login, please wait...")
} else {
Text("Successful login, the username is \(loginObject.username!)")
}
}.onAppear {
self.loginObject.load()
}
}
}
The key here is to avoid trying to make the View
perform anything related to the Model
, except displaying it. SwiftUI
will resist you all the way :-)