SwiftUI previews with multiple modules
Hello,
I've been facing problems with the SwiftUI preview, I have an app that runs clean architecture in multiple modules, SwiftUI preview doesn't work properly running the app scheme, so I had to run specifically the UI module, this works properly in most of the cases but sometimes injecting with @LazyInjected doesn't solve the issue and get the error resetAndTriggerFatalError("\(T.self) was not registered", #file, #line), I tried changing the build configuration to release for that module but for some reason the preview didn't work at all.
public func promised<T>(key: StaticString = #function) -> Factory<T?> {
Factory<T?>(self, key: key) {
#if DEBUG
if self.manager.promiseTriggersError {
resetAndTriggerFatalError("\(T.self) was not registered", #file, #line)
} else {
return nil
}
#else
nil
#endif
}
}
Would probably need a minimum viable project to try and diagnose this.
I'll prepare a quick demo.
Demo:
This demo is a project using clean architecture with multiple modules, where each layer (Data, Domain, and Presentation) is separated into distinct modules. In this setup, the Presentation module is separated into a package, and the App module is responsible for injecting dependencies into the other modules. https://github.com/callo90/factory-demo
Problem:
The error arises because the promised<T>(key: StaticString = #function) -> Factory<T?> doesn’t account for whether it's running the SwiftUI preview mode or not, which causes issues when injecting dependencies.
Fix:
I forked the project and fixed the error by adding a validation for preview mode with FactoryContext.current.isPreview. This allows the preview to continue working without raising errors if dependencies aren't injected, but still triggers an error in other scenarios where it's appropriate.
https://github.com/callo90/factory
https://github.com/hmlongco/Factory/compare/main...callo90:Factory:main?expand=1
Screenshots: Here are some screenshots that highlight the issue:
Let me know if you need anything else!
Hey @hmlongco did you have the chance to review this?
Preview Promise should be fixed in 2.4.0
private var _promiseTriggersError: Bool = FactoryContext.current.isDebug && !FactoryContext.current.isPreview
Great! Left this PR with a similar approach
Hello
I also experienced the same issue, and after testing the fix in the version shared by @callo90, it really seems to work. I want to thank you all for taking the time to address this issue. I’ll be testing version 2.4.0 to confirm if it resolves my problem completely. Thanks again for your effort and support!