Skip to content

Instantly share code, notes, and snippets.

@el-hoshino
Last active August 24, 2024 04:13
Show Gist options
  • Save el-hoshino/9920e3fb89811f76991ff9295da8e35d to your computer and use it in GitHub Desktop.
Save el-hoshino/9920e3fb89811f76991ff9295da8e35d to your computer and use it in GitHub Desktop.
A magic to use `@Environment(\.keyPath)` to extract objects injected by KMP Koin system
final class MyUsecase {} //← Injected KMP type
@dynamicMemberLookup // The magic of everything!
final class DIContainer { // ← Koin DIContainer Wrapper
// let container = // ← Koin DIContainer
subscript<T>(dynamicMember dynamicMember: String) -> T {
// ↓ Replace `fatalError() with injected object using `container` and `T` generics
fatalError()
}
}
// Preparation to use in `@Environment(\.keyPath)`
struct DIContainerKey: EnvironmentKey {
static var defaultValue: DIContainer {
DIContainer()
}
}
extension EnvironmentValues {
var diContainer: DIContainer {
get { self[DIContainerKey.self] }
set { self[DIContainerKey.self] = newValue }
}
}
// SwiftUI View
struct MyView: View {
@Environment(\.diContainer.get) var myUsecase: MyUsecase // ← You can replace `get` with anything and get any object injected to Koin thanks to @dynamicMemberLookup
var body: some View {
EmptyView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment