How to get @Environment or @EnvironmentObject inside ObservableObject
Saw this interesting question on Stackoverflow and thought I would answer it. The trick is to use `DynamicProperty as an intermediary as follows:
class MyObject: ObservableObject {
var context: NSManagedObjectContext? {
didSet {
if oldValue != context {
// do something
}
}
}
}
struct MyProperty: DynamicProperty {
@Environment(\.managedObjectContext) private var viewContext
@StateObject var object = MyObject()
func update() {
// environment vars now are valid
object.context = viewContext
}
}
struct MyView {
var myProperty = MyProperty()
// update is called on myProperty before this
var body: some View {
}
}