0xf1f1
02/25/2024, 12:09 AMddaypunk
02/25/2024, 3:16 PMddaypunk
02/25/2024, 3:17 PM0xf1f1
02/25/2024, 8:18 PMclass 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
}
Ian Lake
02/26/2024, 1:56 AMviewModel
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
methodIan Lake
02/26/2024, 1:58 AMddaypunk
02/26/2024, 2:16 AMIan Lake
02/26/2024, 2:42 AM0xf1f1
02/26/2024, 8:46 AMStylianos Gakis
02/26/2024, 10:36 AMddaypunk
02/27/2024, 1:31 AM