lukacs-m / SpaceXMVVMSwiftUICombine

20 stars 4 forks source link

Changing “Root” #1

Open Reak45 opened 3 years ago

Reak45 commented 3 years ago

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

lukacs-m commented 2 years ago

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.

Reak45 commented 2 years ago

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