[英]Why Does My Lambda Function Not `startExecution` My Step Function
[英]Why does my function not execute while using a DispatchQueue?
有人可以向我解释为什么新视图在 getMsg() 完成执行之前进入吗? 我尝试了许多不同的迭代,但似乎无法弄清楚为什么它不起作用。 onAppear() 有问题吗? 还是与我使用 DispatchQueue 的方式有关?
struct ChatView : View {
@State var msgs = [Msg]()
@EnvironmentObject var msg : msgDatas
let group = DispatchGroup()
var body : some View{
ZStack{
Color("bg").edgesIgnoringSafeArea(.top)
VStack(spacing: 0){
chatTopview()
GeometryReader{_ in
chatList(msgs: self.msg.msgs).onAppear(){
self.group.enter()
DispatchQueue.main.async {
self.getMsgs()
self.group.leave()
}
}
}
}
chatBottomView()
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
func getMsgs() {
let db = Firestore.firestore()
let uid = UserDefaults.standard.value(forKey: "UserName") as! String
db.collection("Private Messages").document(uid).collection("cZQM1Io2azboEUjt42nT6k6TEDF3").order(by: "date", descending: false).addSnapshotListener { (snap, err) in
if err != nil {
print(err!.localizedDescription)
}
/*
if snap!.isEmpty {
}
*/
for i in snap!.documentChanges{
if i.type == .added{
let id = i.document.documentID
let msg = i.document.get("msg") as! String
let user = i.document.get("user") as! String
self.msgs.append(Msg(id: id, msg: msg, user: user))
}
}
}
}
}
你需要像下面这样的东西
VStack(spacing: 0){
chatTopview()
GeometryReader{_ in
if self.msg.msgs.isEmpty {
Text("Loading...") // << some placeholder
} else {
chatList(msgs: self.msg.msgs)
}
}
}
.onAppear(){ // << at this level !!
if self.msg.msgs.isEmpty {
self.getMsgs()
}
}
在回调中,它是异步的并且可以在后台队列上发送,最好执行以下操作
var newMsgs = [Msg]()
for i in snap!.documentChanges{
if i.type == .added{
let id = i.document.documentID
let msg = i.document.get("msg") as! String
let user = i.document.get("user") as! String
newMsgs.append(Msg(id: id, msg: msg, user: user))
}
}
DispatchQueue.main.async {
self.msgs = newMsgs
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.