Getting the KMP viewmodel from swift with koin (cleanest way I guess) #1899
frankois944
started this conversation in
Show and tell
Replies: 2 comments 3 replies
-
here is how I use koin from swift side: Koin.swift typealias KoinApplication = Koin_coreKoinApplication
typealias Koin = Koin_coreKoin
extension KoinApplication {
static let shared = KoinIOSKt.doInitKoinIos(doOnStartup: {
print("Koin started")
}, appDeclaration: { app in
app.properties(values: ["BASE_URL": try! Configuration.value(for: .baseUrl) as String])
})
@discardableResult
static func start() -> KoinApplication {
shared
}
}
func inject<T : AnyObject>() -> T {
return KoinApplication.shared.koin.get(objCClass: T.self) as! T
}
func inject<T : AnyObject>(param: Any?) -> T {
return KoinApplication.shared.koin.get(objCClass: T.self, parameter: param) as! T
} KoinIOS.kt (iOS Main target) @Suppress("unused")
fun initKoinIos(
doOnStartup: () -> Unit,
appDeclaration: KoinAppDeclaration
): KoinApplication {
val koin = initKoin {
module {
single { doOnStartup }
}
appDeclaration()
}
setCrashlyticsUnhandledExceptionHook()
return koin
}
//this currently only excepts single parameter but it can be improved
fun Koin.get(objCClass: ObjCClass, parameter: Any?): Any {
val kClazz = getOriginalKotlinClass(objCClass)!!
return get(kClazz) { parametersOf(parameter) }
}
fun Koin.get(objCClass: ObjCClass): Any {
val kClazz = getOriginalKotlinClass(objCClass)!!
return get(kClazz)
}
fun Koin.get(objCProtocol: ObjCProtocol): Any {
val kClazz = getOriginalKotlinClass(objCProtocol)!!
return get(kClazz)
}
ContentView.swift //ObservedViewModel is from KMP-ObservableViewModel library
@ObservedViewModel private var myViewModel: MyViewModel = inject() This can even be improved with a property wrapper @propertyWrapper
struct Inject<T : AnyObject> {
lazy var wrappedValue: T = { inject() }()
init() { }
} @Inject private var myViewModel: MyViewModel I couldn't find a way to use the property wrapper with |
Beta Was this translation helpful? Give feedback.
1 reply
-
this is not specific to the viewmodels. any class can be injected with this. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi every one,
I found a way to get the KMP viewmodel from a ios/swift project like on Android
Store the koin scope in your swift (or kotlin) code
getOriginalKotlinClass
available from swiftOn iOSMain target :
full exemple at my playground https://github.com/frankois944/kmp-mvvm-exploration
Beta Was this translation helpful? Give feedback.
All reactions