Reputation: 951
Is there any way to inject the ViewModel into composable
function of Compose Multiplatform?
I have tried with Koin dependency injection but it seems not yet ready to inject ViewModel in common module yet. Is there any alternative way or library that can be used in Compose Multiplatform project?
Upvotes: 6
Views: 3880
Reputation: 41
Yes you can by using koin-compose library
First, add this commonMain
commonMain.dependencies {
//...
implementation("io.insert-koin:koin-compose:1.1.2")
}
Now you can inject it through the parameter
fun LoginScreen(viewModel: LoginViewModel = koinInject()) {
}
Keep in mind to configure the ViewModel injection by koin in correct way for android, Ios and JVM:
CommonModule
expect class PlatformModule {
val module: Module
}
val commonModule = module {
includes(userModule, loginModule)
}
MyApp
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
androidContext(this@MyApp)
modules(PlatformModule().module + commonModule)
}
}
}
CommonModule:
actual class PlatformModule {
actual val module: Module = module {
viewModel {
LoginViewModel(get())
}
}
}
CommonModule:
actual class PlatformModule {
actual val module: Module = module {
factory { LoginViewModel(get()) }
}
}
MainKT
fun main() = application {
startKoin {
modules(PlatformModule().module + commonModule)
}
Window(onCloseRequest = ::exitApplication, title = "Movies-KMP") {
App()
}
}
Upvotes: 4
Reputation: 951
I am currently proceeding with manual dependency injection for my use case. But Koin seems working on ways to injecting instances into composable functions. By using, under development function, koinInject() of Koin library, it seems possible to get instances injected. Details can be found here
Upvotes: 0
Reputation: 59
Would you like to try this?
val viewModel = remember { AnyVieweModel() }
Upvotes: -1