when working with compose, whats the best way to p...
# compose
u
when working with compose, whats the best way to pass view model to a screen ? Ive seen normal @ViewModel but then also @HiltViewModel - not sure which is more ideal esp w/ navgraph
d
See here
A lot of information there for interactions between compose and other libraries including view models and navigation
u
thanks. So lets say I have the following:
class MainActivity : ComponentActivity() {
private val db = lazy {
Room.databaseBuilder(
applicationContext,
Database::class.java,
Database.name
).build()
}
private val myviewmodel = ViewModelProvider(this, MyViewModelFactory(repo))[MyViewModel::class.java]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
myComposable()
}
}
]
Will doing the following still work? or must I pass myviewmodel to the composable via the MainActivity
@Composable
fun myComposable(myviewmodel: MyViewModel = viewModel()) {
// do something
}
i
By default, as per the ViewModel scoping guide, the
viewModel
method will get the ViewModel from the closest
ViewModelStoreOwner
, which would indeed be your activity in that code example. However, since you're using a custom Factory, you need to pass that into the
viewModel
method
☝️ 1
You might look at the Create ViewModels with dependencies guide if you aren't using something like Hilt which is doing this for you - the ViewModel factory DSL example there seems like exactly what you need (since your only real dependency is an application context for your Room database)
d
Wouldn’t injecting the db in general be a good idea?
i
Well from the ViewModel's perspective, they're all valid examples of the concept of dependency injection (e.g., the ViewModel doesn't decide where its inputs come from). Dependency injection libraries like Hilt and Koin are certainly quite popular if you want to generate much of that rather than writing it manually
u
is Hilt injection more preferable in my use case ? it seems it'll remove a lot of boilerplate but I;ve had mixed experiences with obscurity and DI in the past with other languages
s
Just try Koin if you do not want all the magic of Hilt. It also has androidx.navigation integration, does not have the hilt magic, but it’s much less safe since it can crash at runtime if you do not hook all the dependencies up correctly. Tradeoffs 😊
👍 1
d
I have koin working with the view model api and compose navigation in one app. It’s fairly straight forward for the most part. Struggling a bit with hilt in general on another even after working with it in a company’s app given I’ve never had to set it up.