https://kotlinlang.org logo
Title
a

abbic

02/22/2023, 1:36 PM
i would like to just write
val router by inject<RouterViewModel>()
but its a compilation error
p

Pedro Alberto

02/22/2023, 2:50 PM
it's a view model you can use
val router: RouterViewModel by viewModel()
a

abbic

02/22/2023, 2:50 PM
its not really a viewmodel :p
p

Pedro Alberto

02/22/2023, 2:51 PM
but you need to provide like viewmodel
a

abbic

02/22/2023, 2:51 PM
im not on android
p

Pedro Alberto

02/22/2023, 2:51 PM
ohhh ok sorry 😞
but where are you trying to inject ?
a

abbic

02/22/2023, 2:51 PM
Inside a Composable function
sorry i accidentally split up my question into 2 messages
(i am using compose multiplatform for desktop jvm)
p

Pedro Alberto

02/22/2023, 2:53 PM
oh wow nice
but the class where you trying to inject that is extending KoinComponent ?
a

abbic

02/22/2023, 2:53 PM
the Composable isnt inside a class
its a global function
p

Pedro Alberto

02/22/2023, 2:53 PM
for composable there is other dependency
but am not sure if this only works for view models
since the injection looks like this
@Composable
fun ViewModelInject(userName : String, viewModel: UserViewModel = koinViewModel()){
    Text(text = viewModel.sayHello(userName), modifier = Modifier.padding(8.dp))
}
a

abbic

02/22/2023, 2:55 PM
theres another example
@Composable
fun FactoryInject(userName : String, presenter: UserStateHolder = get()){
    Text(text = presenter.sayHello(userName), modifier = Modifier.padding(8.dp))
}
but i think that if i tried to use just get, it would still ask me to provide a class parameter
p

Pedro Alberto

02/22/2023, 2:56 PM
so just to undesrtand your RouterViewModel need attributes from the composable ?
a

abbic

02/22/2023, 2:57 PM
let me share a bigger snippet
im early in the project so this is the majority of my code :P
@Composable
@Preview
fun App() {
     val router by inject<RouterViewModel>(RouterViewModel::class.java)

     val routerState: Backstack<AppRoutes> by router.observeStates().collectAsState()

     routerState.renderCurrentDestination(
          route = {
               appRoute ->
               when(appRoute) {
                    AppRoutes.Home -> {
                         HomeScreen()
                    }
               }
          },
          notFound = {}
     )
}

fun main() = application {
    startKoin {
        modules(appModule)
    }
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}
so you see, theres not too much going on. and, to note, this code works
the inject im using isnt from \a class that implements KoinContainer
but the KoinJavaContainer object
p

Pedro Alberto

02/22/2023, 3:00 PM
maybe is the wrong import ?
not sure sisnce I never used koin in KMM