Chain NavigationLinks using Point-Free's swiftui-navigation

115 Views Asked by At

I am testing Point-Free's swiftui-navigation.

It works as expected when I run the app from the first or second screens.

ContentView(viewModel: .init(route: nil))
ContentView(viewModel: .init(route: .second(route: nil))

But, when I run the app from the third screen, the app navigates to the third screen and then pops back to the second.

ContentView(viewModel: .init(route: .second(route: third))

The following code is my current implementation. The preview demonstrates the error.

import SwiftUINavigation
import SwiftUI

class ContentViewModel: ObservableObject {
    @Published var route: Route? = nil

    init(route: Route? = nil) {
        self.route = route
    }

    enum Route: Equatable {
        case second(route: SecondViewModel.Route?)
    }
}

struct ContentView: View {
    @StateObject var viewModel: ContentViewModel

    var body: some View {
        NavigationView {
            NavigationLink(
                unwrapping: $viewModel.route,
                case: /ContentViewModel.Route.second,
                onNavigate: { isActive in
                    viewModel.route = isActive ? .second(route: nil) : nil
                }
            ) { $route in
                SecondView(viewModel: .init(route: route))
            } label: {
                Text("One")
            }
        }
    }
}

class SecondViewModel: ObservableObject {
    @Published var route: Route? = nil

    init(route: Route? = nil) {
        self.route = route
    }

    enum Route: Equatable {
        case third
    }
}

struct SecondView: View {
    @StateObject var viewModel: SecondViewModel

    var body: some View {
        NavigationLink(
            unwrapping: $viewModel.route,
            case: /SecondViewModel.Route.third,
            onNavigate: { isActive in
                viewModel.route = isActive ? .third : nil
            }
        ) { $route in
            Text("Three")
        } label: {
            Text("Two")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(viewModel: .init(route: .second(route: .third)))
    }
}
0

There are 0 best solutions below