Clean up when WindowGroup Window closes

2 days ago 8
ARTICLE AD BOX

I have a WindowGroup declared in my app:

WindowGroup(.workspace, id: "workspace", for: WorkspaceActivityId.self) { $workspaceActivityId in if let workspaceActivityId { if let viewModel = workspaceActivity(id: workspaceActivityId) { WorkspaceActivityView( id: workspaceActivityId, viewModel: viewModel, } } }

I would like to clean up my model whenever the window is closed, so I want to be notified of an event when the window that is created is closed (i.e. my global state has a lot of workspaces, I want to tell the program that it can remove this one since the workspace isn't active anymore).

What's the right way to do this?

I have this on a single Window scene:

.onReceive(NotificationCenter.default.publisher(for: NSWindow.willCloseNotification)) { notification in // Check if this is our window if let window = notification.object as? NSWindow, window.identifier?.rawValue == id.toString() { print("window will close: \(title)") onClose?() } }

And this works because the identifier is stable, but with the group I get an identifier of: workspace-AppWindow-1

Read Entire Article