InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.98k stars 710 forks source link

ViewModel injection issue when using Compose Preview #1705

Closed SirFilbido closed 10 months ago

SirFilbido commented 10 months ago

Describe the bug I'm having problems using Compose's Preview on screens that require a ViewModel and are injected via Koin as the documentation recommends.

java.lang.IllegalStateException: KoinApplication has not been started

Is there already a solution that doesn't use external libraries?

Expected behavior What is expected is the preview loading the screen elements as expected

Koin module and version: koin-androidx-compose:3.5.0

Snippet or Sample project to help reproduce

@Composable
fun MyScreen(navController: NavController) {

    val viewModel = koinViewModel<MyViewModel>()

image image image

arnaudgiuliani commented 10 months ago

You need to wrap your preview with KoinApplicaion and run a small instance of Koin, else it won't find your ViewModel

SirFilbido commented 10 months ago

Thank you for your response @arnaudgiuliani.

I adjusted the preview of my screen, injecting the main module that groups the other modules for injection

That was the result:

@Preview
@Composable
fun MyScreenPreview() {
     KoinApplication(application = {
        modules(appModule()) //Function that groups all DI modules
    }) {
        MyScreen(navController = rememberNavController())
    )
}

I took advantage and abstracted this configuration to another function. I believe it will make it easier to use and I leave it as a tip.

@Preview
@Composable
fun MyScreenPreview() {
    ScreenPreview{
        MyScreen(navController = rememberNavController())
    }
}
@Composable
fun ScreenPreview(
    screen: @Composable () -> Unit
) {
    KoinApplication(application = {
        modules(appModule())
    }) { screen() }
}

I will add other similar issues so that other people in the future can reach this solution