I have View called TransferFlowView() and I have an ObservedObject.
struct TransferFlowView: View { @ObservedObject var transferListVM = TransferListViewModel() }
In TransferListViewModel(), I have a function to Update viewModel.
class TransferListViewModel: ObservableObject { init() { fetch } }
And I call that update function in Modal View. So Whenever I click submit and dismiss Modal View, The
TransferFlowView() is not getting Updated.
I tried using binding property, used .onChange on TransferFlowView. It's not refreshing. I want the view to be loaded, like first time, when it loads.
ObservableObjectrelies on a synthesizes publisherobjectWillChangeto be triggered when there is a change, otherwise a view that observes this object through@ObservedObjectwouldn't know when to refresh.There are two ways to trigger that:
objectWillChange.send()Here if you comment out
objectWillChangeyou will see that the text doesn't change on the view.@Publishedproperty.If you add
@Publishedto the property, it will automatically triggerobjectWillChangewhen you assign a new value. This code will have the same result:You also need to pay attention where you initilize a new instance of
TransferListViewModel. In your current code you use@ObservedObjectand it will be initializing a new instance of the view model every time you refresh the view. For that you have to pass the already initialized instance from outside.Otherwise, you can use
@StateObjectwhich will call the initializer only once.