Share same ViewModel in different Activities (Jetpack Compose, Hilt)

197 Views Asked by At

I have an Jetpack Compose Wear App with a MainActivity with a Navigation Graph and a ViewModel. Now, if I navigate to a specific route (in this case "walk") I want a new activity (WalkActivity) to start, but want the same ViewModel and NavController as in MainActivity. If I use hiltViewModel() it creates a new instance, but I want the same one. I tried activityViewModels() but I get an unresolved reference error. I need a second Activity since I'm using Sensors and you need to create an activity for that. What is the correct/best way to get the same ViewModel and NavController in a different activity?

// MainActivity
@AndroidEntryPoint
@ExperimentalMaterialApi
class MainActivity : ComponentActivity() {
    lateinit var navController: NavHostController

    private lateinit var challengeViewModel: ChallengeViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
                navController = rememberSwipeDismissableNavController()
                challengeViewModel = hiltViewModel()

                CreateNavGraph()
            }
        }
}

// start Activity in Navgraph
...
@Composable
fun CreateNavGraph() {
...
    composable(Screen.Walk.route) {
                val context = LocalContext.current

                context.startActivity(
                    Intent(context, WalkActivity::class.java)
                )
  }
...
}

// WalkActivity
@AndroidEntryPoint
class WalkActivity : ComponentActivity(), SensorEventListener {
    private lateinit var sensorManager: SensorManager
    private var heartRateSensor: Sensor? = null
    private var stepCountSensor: Sensor? = null

    private lateinit var viewModel: ChallengeViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setSensors()

        setContent {
// here I would like to get the viewmodel e.g.
                viewModel = activityViewModels()
                WalkScreen(viewModel = viewModel)
            }
        }
...
}

EDIT I found a solution by myself. Instead of creating a second activity I decided to just create a WalkScreen composable which gets the SensorManager, NavController and ViewModel as a paramter and do my Sensor work in a DisposableEffect.

0

There are 0 best solutions below