Home > Software design >  How to Dismiss view from viewModel in SwiftUI?
How to Dismiss view from viewModel in SwiftUI?

Time:10-23

I have one view with MVVM architecture. in view on button click i am calling webService from viewModel class on success i want to dismiss view.

my viewmodel is ObservableObject

i am moving to other screen using navigation and not using sheet

I have tried this

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
`self.presentationMode.wrappedValue.dismiss()`

in view but it will call before API call.

is there any way to dismiss view once i receive API data in viewModel?

Thank you for help

CodePudding user response:

I didn't compile my code but I think this approach should work. I used something like this in my pet-projects

import SwiftUI
import Combine

class ViewModel: ObservableObject {
    
    var didSendRequest: AnyPublisher<Void, Never> {
        subject.eraseToAnyPublisher()
    }
    
    private let subject = PassthroughSubject<Void, Never>()
}

struct ContentView: View {
    
    var viewModel: ViewModel
    
    @Environment(\.presentationMode)
    var presentationMode
    
    var body: some View {
        VStack {
            Text("Hello")
        }
        .onReceive(viewModel.didSendRequest) { _ in
            presentationMode.wrappedValue.dismiss()
        }
    }
}

In your view model when you receive a response you should execute the next code:

subject.send()

CodePudding user response:

In your ObservableObject, set an @Published var indicating that the API load is complete.

class APIController: ObservableObject {
    @Published var apiLoaded = false;
    
    func doTheApiLoad() {
        ...
        //when you want to dismiss
        DispatchQueue.main.async {
            self.apiLoaded = true;
        }
    }

}

In your content view, watch that published value

@ObservedObject var apiController: APIController()

When it changes, dismiss the view

if (apiController.apiLoaded == true) {
    presentationMode.wrappedValue.dismiss()
}
  • Related