hello all! Any ideas how to share with some compos...
# compose
g
hello all! Any ideas how to share with some composable screens a view model that has been created in the MainActivity?
Copy code
class MainActivity : FragmentActivity() { // I use the FragmentActivity because of biometrics

    private val viewModel: MainViewModel by viewModels()

    MyAppTheme {
          val state by viewModel.state.collectAsStateWithLifecycle()
          val incomingEvent = viewModel.incomingEvent

          MyApp(
              isUserRegistered = state.isUserRegistered,
              hasUserProfile = state.hasUserProfile,
              incomingEvent = incomingEvent
          )
    }
}

@Composable
fun MyApp(
   isUserRegistered: Boolean,
   hasUserProfile: Boolean,
   incomingEvent = incomingEvent
) {
    val navController = rememberAnimatedNavController()

    if (isUserRegistered) {
        NavigationHost(
            Screen.OnboardingDestination.route,
            navController
        )
    } else {
        NavigationHost(
             Screen.MainBashboard.route,
             navController
        )
    }

    when (incomingEvent) {
        is profileEvent -> { 
            navController.navigateToProfileScreen(incomingEvent.getSomeArgs)
        }
        is settingsEvent -> { 
            navController.navigateToSettingsScreen(incomingEvent.getSomeArgs)
        }
        ...
    }
}
Now I need to access the
MainViewModel
from other composable screens that are in the NavigationHost. The reason is that I need to show a specific screen based on an incoming event that I collect from a flow in the
MainViewModel
. The
MainVIewModel
holds some data in memory that I need to access them only from other composables.
f
Now I need to access the
MainViewModel
from other composable screens that are in the NavigationHost
What exactly do you need it for? State can be passed down and events can be passed up using callbacks. There shouldn't be a need for the VM reference
g
@Filip Wiesner I updated my post