I'm using koin in a kmp android & ios project....
# koin
c
I'm using koin in a kmp android & ios project. If I have a shared class in a common module that is using constructor injection, how can I initialise it in iOS? Should I switch to using KoinComponents and injecting with
_by_ inject()
instead? Curious what the best practice is - thanks!
shared/commonMain/UserService.kt
Copy code
class UserService(private val api: UserApi, private val db: UsersDb) {
    //
}
shared/commonMain/KoinDi.kt
Copy code
// called by android application
fun initKoin(appDeclaration: KoinAppDeclaration = {}) =
    startKoin {
        appDeclaration()
        modules(commonModule())
    }

// called by iOS
fun initKoin() = initKoin() {}

fun commonModule() = module {
    single<UserServiceInterface> { UserService(get(), get()) }
}
androidApp/.../UserViewModel.kt
Copy code
class UserViewModel(private val userService: UserService) : ViewModel() { 
    // 
}
iosApp/.../UserViewModel.swift
Copy code
class UserViewModel: ObservableObject {
    private let userService: UserService
    
    init(userService: UserService) {
        self.userService = userService
    }
}
iosApp/.../ContentView.swift
Copy code
struct ContentView: View {
    @StateObject var userViewModel = UserViewModel(userService: UserService(????????))
}
a
there is a cheat sheet about KMP and integration pattern to help run things on iOS: https://blog.cloud-inject.io/kmp-with-koin
c
Great cheat sheet - thanks for letting me know
Now I'm curious about the difference between using a Koin Component vs constructor injection? The docs mention this warning -
Copy code
The KoinComponent interface is here to help you retrieve instances directly from Koin. Be careful, this links your class to the Koin container API. Avoid to use it on classes that you can declare in modules, and prefer constructor injection
For now I'm defining my repository using a constructor, so that android can use constuctor injection. And then I'm adding a helper class like the cheat sheet example for usage in iOS. That seems like the best of both worlds! ...though I'm not entirely sure what benefit I'm getting by still using the constructor injection in Android
a
KoinComponent link your class with the Koin API, i.e: you are calling Koin to retrieve things. Constructor injection means you are called by Koin, no link with it.
👍 1