简体   繁体   中英

Android Jetpack Compose get Activity View Model from Fragment inside Composable

I'm having an issue getting the activity view model from a fragment in a composable

private val birthdayViewModel: BirthdayViewModel by activityViewModels()

When I use viewModels() there is no issue

private val birthdayViewModel: BirthdayViewModel by viewModels()

Fetching the view model in composable like

val birthdayViewModel: BirthdayViewModel = viewModel()
val formItem by birthdayViewModel.birthdayFormItem.observeAsState()

The issue is that the form item errors to null when using activityViewModels but not when using viewModels

When I run in debug mode to check the value of the formItem I get this error message: "Cannot find local variable 'formItem' with type com.form.FormSpec$FormItem"

Could this be a gradle versioning issue?

Please help :)

If you're not using Hilt, assuming that you have instantiated your view model like this in your activity:

val viewModel: YourViewModel by viewModels()

you can get the same instance using this:

val viewModel = viewModel(
    modelClass = YourViewModel::class.java,
    viewModelStoreOwner = LocalContext.current as YourActivity
)
private val activityViewModel: ActivityViewModel by activityViewModels()
private val fragmentViewModel: FragmentViewModel by viewModels()

Composable(fragmentViewModel, activityViewModel)

The problem had to do with scopes. I was not passing the view models into my composable directly, but rather, was doing this in the composable constructor which didn't lead to both of my viewModels having a fragment scope.

Composable(
   fragmentViewModel: FragmentViewModel = viewModel(), 
   activityViewModel: ActivityViewModel = viewModel()
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM