https://kotlinlang.org logo
#compose
Title
# compose
s

sindrenm

03/16/2022, 11:22 AM
Is there a way to scope an AndroidX View Model to a composable, or does that even make sense? AFAICT, when injecting through `viewModel()`/`hiltViewModel()`, the VM is scoped to a
ViewModelStoreOwner
, which might be a nav back stack entry or a fragment or whatnot, but not an “actual” composable, if that makes sense. However, if I have a list of similar items and I want each of them to have their own instance of a same-type View Model, then I'm at a loss on how to achieve this. Any suggestions?
c

curioustechizen

03/16/2022, 11:25 AM
s

sindrenm

03/16/2022, 11:44 AM
I read that the other day, actually, but it doesn't really account for using Dagger/Hilt to inject dependencies, and we're kind of tied into that.
c

curioustechizen

03/16/2022, 11:45 AM
True. We use Koin and I would also like to understand what it takes to integrate that approach with DI
z

Zach Klippenstein (he/him) [MOD]

03/16/2022, 2:41 PM
Why do you need a
ViewModel
at all then? Just use a regular class.
s

sindrenm

03/16/2022, 3:02 PM
I would like to be able to perform network requests and whatnot using Dagger-injected services from each of these View Model instances, and I would prefer having access to
viewModelScope
.
z

Zach Klippenstein (he/him) [MOD]

03/16/2022, 3:06 PM
You can dagger inject any class, not just viewmodels. And you can just pass the coroutine scope from the composition.
s

sindrenm

03/16/2022, 3:07 PM
Fair. I'll definitely give it a go. 👍
a

Arun Joseph

03/17/2022, 1:42 PM
I had tried this https://gist.github.com/manuelvicnt/a2e4c4812243ac1b218b24d0ac8d22bb and it worked with Koin
getViewModel
s

sindrenm

03/18/2022, 8:38 AM
I went with a custom class and connected it with a new Hilt
@EntryPoint
, which seems to work the way it should. Most of the reason for using Jetpack ViewModels so far has been for the convenience of
@HiltViewModel
, `viewModel()`/`hiltViewModel()` and having that just automatically work, but it wasn't too much extra work to tie a regular class into Hilt and whatnot, so we might end up doing this forward. 👍