Last active
August 24, 2024 04:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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