Does anyone have a sample to share of injecting a ...
# kotlin-inject
h
Does anyone have a sample to share of injecting a view model into an
@Composable
function? If I do it as I would for a non-composable function, I get a new view model every time my view is recomposed.
e
I haven't looked at the compose vm integration but I imagine you would want to do it the same way as injecting into fragments, ie you inject the vm factory and call the correct method to have it constructed in the right scope.
h
Thanks @evant. I think I got it working. If you have the time, could you review this short write-up and let me know if anything looks suspect?
e
Looks good, the only thing I'd note is you don't have to use reflection there for the factory, you can just construct the instance directly
Oh yeah, you can also save creating a factory for each vm, by injecting a function instead, since kotlin-inject can create that for you:
Copy code
@Composable
fun ProfileScreen(vmFactory: () -> ProfileViewModel) {
   val viewModel: ProfileViewModel = viewModel(factory = object : ViewModelProvider.Factory {
      override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return vmFactory() as T
   })
}
you way also works though
h
Thanks, I removed the unnecessary declarations from
AppComponent
.
I'm not sure I follow your second suggestion. I'll have to study it a bit.
e
here's the section in the docs if that helps https://github.com/evant/kotlin-inject#function-support
h
Thanks! I'll give it a try in my project