Issue #831
We can normally listen to sub ObservableObject
by either listen to its objectWillChange
or its Publisher
class SubModel: ObservableObject {
@Published var count = 0
}
class AppModel: ObservableObject {
@Published var submodel: SubModel = SubModel()
private var bag = Set<AnyCancellable>()
init() {
submodel.$count
.sink(receiveValue: { [weak self] _ in
self?.objectWillChange.send()
})
}
}
We can then make a convenient extension to ease this. We use DispatchQueue
to trigger objectWillChange
in another run loop, to achieve didSet
behavior
import SwiftUI
import Combine
extension ObservableObject where ObjectWillChangePublisher == ObservableObjectPublisher {
func dependsOn<T>(publisher: Published<T>.Publisher) -> AnyCancellable {
publisher
.sink(receiveCompletion: { _ in }, receiveValue: { [weak self] _ in
DispatchQueue.main.async {
self?.objectWillChange.send()
}
})
}
}
class AppModel: ObservableObject {
@Published var submodel: SubModel = SubModel()
private var bag = Set<AnyCancellable>()
init() {
dependsOn(publisher: submodel.$count)
.store(in: &bag)
}
}