Best-practices to download data from server in SwiftUI

后端 未结 3 772
有刺的猬
有刺的猬 2021-02-10 16:16

My question is a conceptual question.

I have the following code:

struct CategoriesList : View {

    @State pri         


        
3条回答
  •  执念已碎
    2021-02-10 16:28

    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 :-)

提交回复
热议问题