ObservedObject inside ObservableObject not refreshing View
Nested ObservableObjects is not supported yet. When you want to use these nested objects, you need to notify the objects by yourself when data got changed. I hope the following code can help you with your problem.
First of all use: import Combine
Then declare your model and submodels, they all need to use the @ObservableObject
property to work. (Do not forget the @Published
property aswel)
I made a parent model named Model and two submodels Submodel1 & Submodel2. When you use the parent model when changing data e.x: model.submodel1.count
, you need to use a notifier in order to let the View update itself.
The AnyCancellables notifies the parent model itself, in that case the View will be updated automatically.
Copy the code and use it by yourself, then try to remake your code while using this. Hope this helps, goodluck!
class Submodel1: ObservableObject {
@Published var count = 0
}
class Submodel2: ObservableObject {
@Published var count = 0
}
class Model: ObservableObject {
@Published var submodel1 = Submodel1()
@Published var submodel2 = Submodel2()
var anyCancellable: AnyCancellable? = nil
var anyCancellable2: AnyCancellable? = nil
init() {
anyCancellable = submodel1.objectWillChange.sink { [weak self] (_) in
self?.objectWillChange.send()
}
anyCancellable2 = submodel2.objectWillChange.sink { [weak self] (_) in
self?.objectWillChange.send()
}
}
}
When you want to use this Model, just use it like normal usage of the ObservedObjects.
struct Example: View {
@ObservedObject var obj: Model
var body: some View {
Button(action: {
self.obj.submodel1.count = 123
// If you've build a complex layout and it still won't work, you can always notify the modal by the following line of code:
// self.obj.objectWillChange.send()
}) {
Text("Change me")
}
}
If you have a collection of stuff you can do this:
import Foundation
import Combine
class Submodel1: ObservableObject {
@Published var count = 0
}
class Submodel2: ObservableObject {
var anyCancellable: [AnyCancellable] = []
@Published var submodels: [Submodel1] = []
init() {
submodels.forEach({ submodel in
anyCancellable.append(submodel.objectWillChange.sink{ [weak self] (_) in
self?.objectWillChange.send()
})
})
}
}