Is there any way to inject ViewModel into composab...
# compose-ios
a
Is there any way to inject ViewModel into composable function in Compose Multiplatform?
👍 1
k
val viewModel = remember { AnyViewModel() }
a
Thanks for your suggestion. But I have some other dependencies that will be inject into viewModel and I don’t want to manually push them all one by one. Is there any alternative?
d
I prefer manual DI pattern using Kotlin objects as providers, exposing functions to create viewmodel. The bulk of dependencies are served between the Kotlin provider objects only, so the view only needs to see a parameter-less create function (or limited number of parameters that we really care about being different).
This is similar to DI frameworks. I think given Java's verbosity DI frameworks were more important then. Kotlin offering objects, lazy vals, default parameters etc all make manual DI easier to manage now. There's value in it being pure Kotlin without yet another framework for team members to learn.
d
And then of course, let's remind that ContextReceivers are coming soon, which will finally remove any need for third party DI frameworks
d
...can you expand on what you mean by that, @Daniele B?
a
@darkmoon_uk Thank you for your suggestion. Yeah, I’m currently working with manual dependency injection. But it would be better to have a dependency injection library like Hilt.
@Daniele B May I know some more details please?
d
But it would be better to have a dependency injection library like Hilt.
Have you had good experiences with these frameworks, or is a received assumption that they would improve things? Every usage of Dagger and Hilt that I've encountered has harmed productivity by adding unnecessary complexity, 'magic' and build time to a project. This may have all been worth it in the Java days but I believe Kotlin now offers all we need.
d
@Ahsan Ullah Rasel @darkmoon_uk it'a explained very well in the first part of this talk:

https://youtu.be/2oiRCYnqhDs

v
Well if you have DI fraemwork then you add the ViewModel dependency to the graph (If you want android VM to be created through the android's vm providers, you add it from target sets). And then you check if the fraemwork provides integration with the Compose MP to fetch the VM from the di. If not - you implement your @Composable
Copy code
inline fun <reified T : BaseViewModel> provideViewModel(): T
to fetch the VM from DI graph
s
I've been using koin-compose https://insert-koin.io/docs/reference/koin-compose/multiplatform for DI via
koinInject()
in the method.
158 Views