Best-practices to download data from server in SwiftUI

后端 未结 3 774
有刺的猬
有刺的猬 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:39

    The SwiftUI community hasn't really established any best-practices yet because the technology is so new. My answer is based off of what I've seen from different WWDC19 sessions.

    First, create a BindableObject with a categories property. Then write your network request code and set self.categories to your newly downloaded categories.

    import SwiftUI
    import Combine
    
    final class CategoryStore: BindableObject {
        var didChange = PassthroughSubject()
    
        var categories = [String]()
    
        init() {
            // TODO: Fetch categories from API
            self.categories = ["A", "B", "C"]
        }
    }
    

    Then, add CategoryStore to View and use it with List to iterate over the categories.

    import SwiftUI
    
    struct ContentView : View {
        @ObjectBinding private var store = CategoryStore()
    
        var body: some View {
            List(store.categories.identified(by: \.self)) { category in
                Text(category)
            }
        }
    }
    

    Whenever the categories property updates, your UI will update with the new categories (tysm Combine)

提交回复
热议问题