Christopher Mederos
11/14/2023, 12:38 AM_by_ inject()
instead? Curious what the best practice is - thanks!Christopher Mederos
11/14/2023, 12:43 AMclass UserService(private val api: UserApi, private val db: UsersDb) {
//
}
shared/commonMain/KoinDi.kt
// 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
class UserViewModel(private val userService: UserService) : ViewModel() {
//
}
iosApp/.../UserViewModel.swift
class UserViewModel: ObservableObject {
private let userService: UserService
init(userService: UserService) {
self.userService = userService
}
}
iosApp/.../ContentView.swift
struct ContentView: View {
@StateObject var userViewModel = UserViewModel(userService: UserService(????????))
}
arnaud.giuliani
11/14/2023, 8:19 AMChristopher Mederos
11/14/2023, 10:10 PMChristopher Mederos
11/14/2023, 10:14 PMThe 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 Androidarnaud.giuliani
11/15/2023, 8:42 AM