SpaceXMVVMSwiftUICombine icon indicating copy to clipboard operation
SpaceXMVVMSwiftUICombine copied to clipboard

Changing “Root”

Open Reak45 opened this issue 4 years ago • 2 comments

Hello! Thank you so much for the article and the repository! They are both very helpful! However, I have encountered an issue in my personal project that I cannot resolve on my own.

When the User first launches the app, I want him/her to complete a registration flow (a couple of views which can be navigated back). After that I’d like to set Main view as the root from which the user would be able to navigate to various subsections of the app and navigate back to the Main. How can I do that?

Thank you, Aro

Reak45 avatar Dec 09 '20 21:12 Reak45

Hello @Reak45, If I understand correctly your question you would like to have a login flow that brings you to a new entry point of your app once finished? For that I would set up a root view and root ViewModel that would have access to the registration state of the current user. This information should be coming from a service / repository. This user state would then determine the view exposed by root view.

Main app entry point

@main
struct MainApp: App {
    var body: some Scene {
        WindowGroup {
            RootView()
        }
    }
}

Root View

struct RootView: View {
    @StateObject private var viewModel: RootViewModel

    var body: some View {
        if viewModel.userIsConnected {
         Text("GO to maintabbar")
        } else { 
           Text("login flow")
        }
    }
}

Root ViewModel

final class RootViewModel: ObservableObject {
    @Published private(set) var userIsConnected: Bool = false
    private var authenticationRepository: AuthenticationProceedings

    private var cancellables = Set<AnyCancellable>()

    init() {
        setUp()
    }
}

extension RootViewModel {
    private func setUp() {
        authenticationRepository.isAuthenticated
            .receive(on: DispatchQueue.main)
            .assignNoRetain(to: \. userIsConnected, on: self)
            .store(in: &cancellables)
    }
}

Hope this helps.

lukacs-m avatar Jan 04 '22 10:01 lukacs-m

Thank you for your response! In the end I implemented a similar logic in my app :)

Reak45 avatar Jan 04 '22 10:01 Reak45