0

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)))
    }
}
3
  • Never used point free but any setup that relies on creating view models on the init of the view and by exposing a StateObject by making it public doesn’t understand SwiftUI Commented Apr 21, 2023 at 11:32
  • StateObject should always be private developer.apple.com/documentation/swiftui/stateobject Commented Apr 21, 2023 at 11:33
  • There are also issues with the package that could be causing it such as using ObservedObject to initialize reference types, there is no way to maintain identity. I would suggest looking into another setup. Commented Apr 21, 2023 at 11:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.