NavigationStack with @Observable won’t works

do you know how to ensure continuous navigation in our app from the main screen to screen 1 and from screen 1 to screen 2 using append on NavigationPath? Unfortunately, in my example, it only works for one step and then stops being observed. Do you know what I’m doing wrong?

Step to reproduce:

  1. Tap “Go to view1” button
  2. Tap “Go to view 2” button

Expected:

  • User see “View 2” text
  • I don’t won’t use EnvironmentObject if no needed
import SwiftUI

@Observable @MainActor
final class MainClass {
    
    public enum Destination: Hashable {
        case view1(Class1)
        case view2(Class2)
    }
    
    var path: [Destination]
    
    init(path: [Destination] = []) {
        self.path = path
    }
}

@Observable @MainActor
final class Class1: Hashable {
    
    var path: [MainClass.Destination]
    
    init(path: [MainClass.Destination] = []) {
        self.path = path
    }
    
    
    nonisolated static func == (lhs: Class1, rhs: Class1) -> Bool {
        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
    }

    nonisolated func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
}

struct View1: View {
    @Bindable var model: Class1
    var body: some View {
        Button("View 1") {
            model.path.append(.view2(Class2(path: model.path)))
        }
    }
}

@Observable @MainActor
final class Class2: Hashable {
    
    var path: [MainClass.Destination]
    
    init(path: [MainClass.Destination] = []) {
        self.path = path
    }
    
    nonisolated static func == (lhs: Class2, rhs: Class2) -> Bool {
        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
    }

    nonisolated func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
}

struct View2: View {
    @Bindable var model: Class2
    var body: some View {
        Text("View 2")
    }
}

@MainActor
struct ContentView: View {
    @Bindable var mainClass = MainClass()
    
    var body: some View {
        NavigationStack(path: $mainClass.path) {
            Button("Go to view 1") {
                mainClass.path.append(.view1(.init(path: mainClass.path)))
            }
            .padding()
            .navigationDestination(for: MainClass.Destination.self) { destination in
                switch destination {
                case let .view1(model):
                    View1(model: model)
                case let .view2(model):
                    View2(model: model)
                }
            }
        }
    }
}

#Preview {
    ContentView()
}

You have two separate path variables that don’t know about each other in Class1 and Class2. For the path to work properly, you essentially need a shared variable passed throughout the Stack.

I would move the path out of the model and into the view. So like this:

import SwiftUI

enum ViewType {
    case view1, view2
}

struct View1: View {
    @Binding var path: NavigationPath
    var body: some View {
        Text("View 1")
        NavigationLink("Go to view 2", value: ViewType.view2)
    }
}

struct View2: View {
    @Binding var path: NavigationPath
    var body: some View {
        Text("View 2")
    }
}

@MainActor
struct ContentView: View {
    @State private var path = NavigationPath()
    
    var body: some View {
        NavigationStack(path: $path) {
            Button("Go to view 1") {
                path.append(ViewType.view1)
            }
            .padding()
            .navigationDestination(for: ViewType.self) { destination in
                switch destination {
                case .view1:
                    View1(path: $path)
                case ViewType.view2:
                    View2(path: $path)
                }
            }
        }
    }
}

#Preview {
    ContentView()
}

Note the use of @Binding – this lets other views observe the path and make changes to it.

You can add more views to the enum if needed, set the path to NavigationPath() to go back to the root view, create a variable in the enum if you still need to pass in the model. Here’s a pretty thorough rundown of NavigationStack that was helpful to me: https://www.swiftyplace.com/blog/better-navigation-in-swiftui-with-navigation-stack

2

Hi all I finally found solution based on pointfree https://github.com/pointfreeco/syncups/tree/main.

Here is the code if anyone is interested. If somebody see any issue there please comment 🙂

import SwiftUI
import SwiftUINavigation
import DependenciesMacros

@Observable @MainActor
final class MainClass {
    
    public enum Destination: Hashable {
        case view1(Class1)
        case view2(Class2)
    }
    
    var path: [Destination] {
        didSet { self.bind() }
    }
    
    init(path: [Destination] = []) {
        self.path = path
    }
    
    func next() {
        path.append(.view1(Class1()))
    }
    
    private func bind() {
        for destination in self.path {
            switch destination {
            case let .view1(model):
                bindView1(model: model)
            case let .view2(model):
                bindView2(model: model)
            }
        }
    }
    
    func bindView1(model: Class1) {
        model.onNextTapped = { [weak model, weak self] in
            guard let model else { return }
            self?.path.append(.view2(Class2()))
        }
    }
    
    func bindView2(model: Class2) {
        model.onEndTapped = { [weak model, weak self] in
            guard let model else { return }
            self?.path = []
        }
    }
}

@Observable @MainActor
final class Class1: HashableObject {
    
    @DependencyEndpoint
    @ObservationIgnored
    var onNextTapped: () -> Void = {  }
    
    func next() {
        onNextTapped()
    }
}

struct View1: View {
    @Bindable var model: Class1
    
    var body: some View {
        Button("Go to view 2") {
            model.next()
        }
    }
}

@Observable @MainActor
final class Class2: HashableObject {
    
    @DependencyEndpoint
    @ObservationIgnored
    var onEndTapped: () -> Void = {  }
    
    func next() {
        onEndTapped()
    }
    
}

struct View2: View {
    @Bindable var model: Class2
    var body: some View {
        Button("View 2") {
            model.onEndTapped()
        }
    }
}

@MainActor
struct ContentView: View {
    @Bindable var mainClass = MainClass()
    
    var body: some View {
        NavigationStack(path: $mainClass.path) {
            Button("Go to view 1") {
                mainClass.next()
            }
            .padding()
            .navigationDestination(for: MainClass.Destination.self) { destination in
                switch destination {
                case let .view1(model):
                    View1(model: model)
                case let .view2(model):
                    View2(model: model)
                }
            }
        }
    }
}

#Preview {
    ContentView()
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật