我有如下所示的ViewModel:
class ItemsListViewModel : ObservableObject{
var response : ItemsListResponse? = nil
var itemsList : [ListItem] = []
var isLoading = true
let objectWillChange = PassthroughSubject<Void, Never>()
func getItems() {
self.isLoading = true
ApiManager.shared.getItems()
.sink(receiveCompletion: {completion in
}, receiveValue: {
self.response = data
self.isLoading = false
self.objectWillChange.send()
})
}
}
当我收到来自网络请求的数据时,我使用self.objectWillChange.send()
通知视图,但是视图对此不做出反应。
我的观点:
ItemsView
struct ItemsView: View {
var body: some View {
VStack{
Text("Some Title")
ItemsListView()
}
}
}
ItemsListView
struct ItemsListView: View {
@ObservedObject var myViewModel = ItemsListViewModel()
var body: some View {
VStack{
Text("\(self.myViewModel.response?.total")
}.onAppear{
self.myViewModel.getItems()
}
}
}
但是有趣的是,如果我不使用 ItemsListView ItemsView 一切正常。我该如何解决这个问题?
答案 0 :(得分:1)
尝试一下(我只是简化了您的模型以在操场上进行测试)
您可以直接在操场上复制代码并检查
struct Model {
var items : [String]
}
class ItemsListViewModel : ObservableObject {
@Published var items : [String] = ["Test 1", "Test2"]
}
let myViewModel = ItemsListViewModel()
struct ItemsView: View {
var body: some View {
VStack{
Text("Some Title")
ItemsListView().environmentObject(myViewModel)
}
}
}
struct ItemsListView: View {
@EnvironmentObject private var model : ItemsListViewModel
var body: some View {
VStack{
Text("\(model.items.count)")
}
}
}
struct ContentView: View {
var body: some View {
ItemsView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(myViewModel)
}
}
答案 1 :(得分:0)
使用@Published作为ObservableObject的属性确实可以解决您的问题。参见以下简化的演示:
implementation 'com.google.firebase:firebase-core:xx.x.x'