frzi / swiftui-router

Path-based routing in SwiftUI
MIT License
900 stars 43 forks source link

Keep paths loaded in memory for performance (e.g. in tab bar) #62

Open jeanbaptistebeau opened 1 year ago

jeanbaptistebeau commented 1 year ago

Is there a way to keep some paths loaded in memory, i.e. not recreate the views when the path changes?

I was implementing a tab bar layout like in the RandomUsers example, but with this solution the pages get recreated every time the user switches tab, which can make the process of switching tab a bit laggy.

Is there a way to keep those pages in memory to provide a smooth tab bar experience?

Note: this would also allow keeping states, like scrolling positions. It just feels more natural.

frzi commented 1 year ago

No, this is beyond the scope of SwiftUI Router and would probably require a significant rewrite of the framework. It also raises questions like what the state is based on. The path of the Navigator or the path of the Route (which may contain placeholders)?

Sadly as the framework currently works you're somewhat forced to keep track of states yourself (which I understand is very difficult when it comes to scrollviews et al) 😞

stevenb9 commented 1 year ago

I was able to workaround this by using Factory dependency injection (https://github.com/hmlongco/Factory).

  1. Register your view as a singleton (static let myService = Factory(scope: .singleton) { View() as View }
  2. Inject the singleton view in your TabContents (@Injected(Container.myService) private var map )
  3. For the route, hse this injected variable as the content (Route("/tabbar/map/*", content: map))

This will keep the view in memory