app
app copied to clipboard
[Optional] Environment-based Routing
@tillkruss you're getting this for free 🎉🆓🎉, if you want it.
I was messing about in SwiftUI today, on my free time. Stumbled upon something I liked a decided to stress test it on your project.
As briefly mentioned before, SwiftUI @Environment
is also a way of doing dependency injection (I use it in some of my recent codebases). The code above allows us to automatically inject multiple Routers into the environment with very little boilerplate. So every view gets to have its own Router type but its still possible to deeplink programmatically to pretty much any screen.
Notes:
- Imho this is peak SwiftUI 😀, but it also uses some complex code (with weird syntax) internally. The global router was fine too, so I'll understand if you don't merge this. If needed, I could cleanup the "public" syntax which we'll realistically use (e.g. when defining previews or tests), internal syntax can stay weird 🙂.
- Having multiple routers avoids "domain leakage", i.e. a view operates on its router's
path
as opposed to some global router'smoviesPath
orsettingsPath
or even deeper structures. The code is more modular. - In this example
switchToNewInstance
is a little overengineered to show that the views can even be decoupled to some extent. We could have just used TabRouter and SettingsView.Router directly in MoviesView.
Its a draft PR for now because I still have to uncomment some Preview code and clean up. Take it or leave it. If Im doing the cleanup, I'll start tracking time, but it'll be a few minutes.