Reputation: 6475
I'm looking for a way of observing @State
or @Binding
value changes in onReceive
. I can't make it work, and I suspect it's not possible, but maybe there's a way of transforming them to Publisher
or something while at the same time keeping the source updating value as it's doing right now?
Below you can find some context why I need this:
I have a parent view which is supposed to display half modal based on this library: https://github.com/AndreaMiotto/PartialSheet
For this purpose, I've created a @State private var modalPresented: Bool = false
and I'm using it to show and hide this modal view. This works fine, but my parent initializes this modal immediately after initializing self, so I completely loose the onAppear
and onDisappear
modifiers. The problem is that I need onAppear
to perform some data fetching every time this modal is being presented (ideally I'd also cancel network task when modal is being dismissed).
Upvotes: 1
Views: 510
Reputation: 17572
use ObservableObject / ObservedObject instead.
an example
import SwiftUI
class Model: ObservableObject {
@Published var txt = ""
@Published var editing = false
}
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
TextField("Email", text: self.$model.txt, onEditingChanged: { edit in
self.model.editing = edit
}).onReceive(model.$txt) { (output) in
print("txt:", output)
}.onReceive(model.$editing) { (output) in
print("editing:", output)
}.padding().border(Color.red)
}
}
Upvotes: 1