QuickBirdEng / XCoordinator

🎌 Powerful navigation library for iOS based on the coordinator pattern
MIT License
2.25k stars 177 forks source link

Is there any way to define Router object in single instance? #238

Open canbalkaya opened 1 year ago

canbalkaya commented 1 year ago

I always define a Router object when a view model's initializing. I want to see my view controllers at Xcode preview, that's why I need to define Router objects at preview state. Is it possible?

pauljohanneskraft commented 1 year ago

@canbalkaya Interesting idea - what exactly should happen, if a route is triggered? You might for example want to define something like this:

#if targetEnvironment(simulator)

private var routerCollection = [ObjectIdentifier: Any]()

extension UnownedRouter {

    static func preview<RouteType>() -> Self where Value == StrongRouter<RouteType> {
        let identifier = ObjectIdentifier(self)
        if let existing = routerCollection[identifier] as? StrongRouter<RouteType> {
            return .init(existing) { $0 }
        }
        let coordinator = BasicViewCoordinator<RouteType>(rootViewController: .init()) { route in
            print("prepareTransition(for:)", route)
            return .none()
        }
        let router = coordinator.strongRouter
        routerCollection[identifier] = router
        return .init(router) { $0 }
    }

}

#endif

Of course, you could make your previews even more sophisticated by creating the coordinator in a better way, but maybe this idea helps for a start? What do you think about it?