3

I'm trying to for example change the title of the appBar or whether the bottomNavBar should be shown in different composables. Since I don't want to pass that viewModel to every composable, I've created a viewModel called AppViewModel and inject it with Hilt to change these values, The mentioned viewModel is like this:

@HiltViewModel
class AppViewModel @Inject constructor(): ViewModel() {
    var showBottomNavBar = mutableStateOf(true)
}

In my main activity

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val appViewModel = hiltViewModel<AppViewModel>()
            val showBottomNavbar by remember {appViewModel.showBottomNavBar}
            AppTheme {
                val navController = rememberNavController()
                Scaffold(
                    bottomBar = {
                        if (showBottomNavbar)
                            BottomNavigation1(navController = navController)
                    }
                ) {
                    Box(Modifier.padding(it)) {
                        NavigationGraph(navController = navController)
                    }
                }
            }
        }
    }
}

And in one of my destination composables like the one below If I change the showBottomNavbar it doesn't change anything.

@Composable
fun Product(
    navController: NavController,
    appViewModel: AppViewModel = hiltViewModel()
) {
    LaunchedEffect(Unit) {
        appViewModel.showBottomNavBar.value = false
    }
}

What am I doing wrong and how can I achieve the what I'm looking for? Thanks in advance.

Arman Momeni
  • 650
  • 1
  • 9
  • 27
  • 1
    Since you are not passing down the ViewModel, each composable with `appViewModel: AppViewModel = hiltViewModel()` would create a new `AppViewModel` if it is not passed. – Abhimanyu Apr 11 '22 at 17:17
  • @Abhimanyu https://stackoverflow.com/a/69221534/5097103 I read here that the top most call will create it and it is a singleton through out the app the rest of the calls will give the same object. – Arman Momeni Apr 11 '22 at 17:33
  • 1
    You've missed this part of the linked answer: "The exception to this is different destinations of Compose Navigation, see how to handle this case in [this answer](https://stackoverflow.com/a/68857871/3585796)." – Phil Dukhov Apr 12 '22 at 03:11
  • @PylypDukhov That doesn't help either if you have other viewmodels injected to composables if it keeps the same storeowner – Arman Momeni Apr 12 '22 at 10:47
  • You should be using SavedStateHandle in your AppViewModel, that's for sure. – EpicPandaForce Apr 23 '22 at 23:48

0 Answers0