Search code examples
androidkotlinandroid-jetpack-composeandroid-viewmodel

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 :)


Solution

  • 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()
    )