'How to call method in view from viewmodel in swift?

I am having view and viewmodel in swiftUi in view i have one function to show alert which need to call when API call get failed. API functionality is written in view model, I am not sure how to call method from view when api gives error in viewmodel.

//View

  @State private var showDialogBox = false

  func action(message: String) {
        showDialogBox.toggle()
  }

  var body: some View {
        VStack(alignment: .leading, spacing: .afklSpacingL) {
            Text(TranslationKeys.selectPassengerTitle.title)
        }
  }
    .overlay(showDialogBox ? AnyView(DialogBoxTwoButtons(accessibilityID: "dialogboxes", dialogboxType: .warning, dialogboxTitle: "Title", dialogboxBody: "body", dialogboxFirstButtonTitle: "Ok", dialogboxFirstButtonCallback: { action(message: "Ok") }, dialogboxSecondButtonTitle: "Cancel", dialogboxSecondButtonCallback: { action(message: "Cancel") }, isDialogboxFirstButtonClicked: $isDialogboxFirstButtonClicked, isDialogboxSecondButtonClicked: $isDialogboxSecondButtonClicked)
            ) : AnyView(EmptyView()))

//Viewmodel

extension abcViewModel: Listener {

    func apiCall(error: KitError?, uuid: UUID) {
        if error == nil,
           
        } else {
             //call "action" method in View to show dialog box
        }
    }
}


Solution 1:[1]

What should a ViewModel be capable of?

The view model is an abstraction of the view exposing the public properties and commands. Instead of the controller of the MVC pattern, or the presenter of the MVP pattern, MVVM has a binder, which automates communication between the view and its bound properties in the view model.

What you should be doing is create a shared Instance of your ViewModel Or you can use a coordinator for that but for your solution shared instance can be used in your view. Just like this

class abcViewModel {
   static var shared = abcViewModel()
   func apiCall(error: KitError?, uuid: UUID) {
       if error == nil{
       
       } else {
            //call "action" method in View to show dialog box
       }
   }

}

And in your view

var viewModel = abcViewModel.shared

Now your public methods are available in your view class.

There might be even better options out there. Everyone here is for learning. Thanks.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Asad