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

0xf1f1

02/25/2024, 12:09 AM
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

ddaypunk

02/25/2024, 3:16 PM
See here
A lot of information there for interactions between compose and other libraries including view models and navigation
u

0xf1f1

02/25/2024, 8:18 PM
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

Ian Lake

02/26/2024, 1:56 AM
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

ddaypunk

02/26/2024, 2:16 AM
Wouldn’t injecting the db in general be a good idea?
i

Ian Lake

02/26/2024, 2:42 AM
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

0xf1f1

02/26/2024, 8:46 AM
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

Stylianos Gakis

02/26/2024, 10:36 AM
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

ddaypunk

02/27/2024, 1:31 AM
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.