如何在SwiftUI下使用异步调用关闭来初始化参数

时间:2020-03-04 06:28:03

标签: swiftui

我尝试在init()方法下初始化一个值,但出现此错误 转义转义捕获突变的'self'参数

如果我将它放在onAppear()下会起作用,但是如果屏幕在后组上就不会调用,所以这不是我需要的。附上我的编码..

struct GameRowForDemo: View {

    let game : Game
    var user : User?


    init(game:Game){
        self.game = game
        let uid = "123"
        User.getById(id: uid).then { user in
            self.user = user!
        }
    }




    var body: some View {
        Text("Text")
    }
}

static func getById(id: String) -> Promise<User?>  {
    let p = Promise<User?> { (resolve , reject) in
        let db = Firestore.firestore()
        let ref = db.collection("users").document(id)
        ref.getDocument { (snapshot, err) in
            if let err = err{
                reject(err)
            }
            guard let dict = snapshot?.data() else {
                print("No User found")
                resolve(nil)
                return
            }
            do {
                let data = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
                let group = try JSONDecoder.init().decode(User.self, from: data)
                resolve(group)
            }catch{
                reject(error)
            }
        }
    }
    return p
}

1 个答案:

答案 0 :(得分:0)

由于这里的视图是不变的,因此我将通过将相关内容分解为如下所示的显式视图模型来重构提供的代码

import Combine

class GameViewModel: ObservableObject {
    @Published var game : Game
    @Published var user : User?

    init(game: Game) {
        self.game = game
    }

    func fetchUser(uid: String) {
        User.getById(id: uid).then {[weak self] user in
            DispatchQueue.main.async {
                self?.user = user!
            }
        }
    }
}

struct GameRowForDemo: View {
    @ObservedObject var viewModel: GameViewModel

    init(viewModel: GameViewModel) {
        self.viewModel = viewModel
        viewModel.fetchUser(uid: "123")
    }

    var body: some View {
        Text("Text")
    }
}