Fix remaining retain cycles, allow coordinators to be weakly referenced and make sure the NavigationStackCoordinator cleans up after itself

This commit is contained in:
Stefan Ceriu
2023-02-02 10:15:31 +02:00
committed by Stefan Ceriu
parent 93997efef9
commit 594f6f85dd
14 changed files with 63 additions and 36 deletions
@@ -17,7 +17,7 @@
import SwiftUI
@MainActor
protocol CoordinatorProtocol {
protocol CoordinatorProtocol: AnyObject {
func start()
func stop()
func toPresentable() -> AnyView
@@ -213,14 +213,14 @@ class NavigationSplitCoordinator: CoordinatorProtocol, ObservableObject, CustomS
///
/// For added complexity, the NavigationSplitCoordinator has an internal compact layout NavigationStack for which we need to manually nil things again
private func releaseAllCoordinatorReferences() {
sidebarModule?.coordinator = nil
detailModule?.coordinator = nil
sheetModule?.coordinator = nil
fullScreenCoverModule?.coordinator = nil
sidebarModule?.tearDown()
detailModule?.tearDown()
sheetModule?.tearDown()
fullScreenCoverModule?.tearDown()
compactLayoutRootModule?.coordinator = nil
compactLayoutRootModule?.tearDown()
compactLayoutStackModules.forEach { module in
module.coordinator = nil
module.tearDown()
}
}
@@ -594,6 +594,19 @@ class NavigationStackCoordinator: ObservableObject, CoordinatorProtocol, CustomS
.presentationDetents(presentationDetents))
}
/// The NavigationStack has a tendency to hold on to path items for longer than needed. We work around that by manually nilling the coordinator
/// when a NavigationModule is dismissed. As the NavigationModule is just a wrapper multiple instances of it continuing living is of no consequence
/// https://stackoverflow.com/questions/73885353/found-a-strange-behaviour-of-state-when-combined-to-the-new-navigation-stack/
func stop() {
rootModule?.tearDown()
sheetModule?.tearDown()
fullScreenCoverModule?.tearDown()
stackModules.forEach { module in
module.tearDown()
}
}
// MARK: - CustomStringConvertible
var description: String {
@@ -27,7 +27,7 @@ class NavigationModule: Identifiable, Hashable {
/// As the NavigationModule is just a wrapper multiple instances of it continuing living is of no consequence
/// https://stackoverflow.com/questions/73885353/found-a-strange-behaviour-of-state-when-combined-to-the-new-navigation-stack/
var coordinator: (any CoordinatorProtocol)?
let dismissalCallback: (() -> Void)?
var dismissalCallback: (() -> Void)?
init(_ coordinator: any CoordinatorProtocol, dismissalCallback: (() -> Void)? = nil) {
self.coordinator = coordinator
@@ -38,6 +38,7 @@ class NavigationModule: Identifiable, Hashable {
coordinator?.stop()
dismissalCallback?()
coordinator = nil
dismissalCallback = nil
}
nonisolated static func == (lhs: NavigationModule, rhs: NavigationModule) -> Bool {