# compose

Chris Fillmore

04/27/2022, 4:02 PM
I am trying to implement a timeout on app backgrounding, because I have several open socket connections with stateful services. I am using Compose navigation with a VM scoped to a “Main” screen.
So I have something like this:
Copy code
composable( { navBackStackEntry ->

  // MyViewModel holds a component with several open connections, which I want to clean up
  // if the app is in the backgrounding for some amount of time.
  val viewModel = hiltViewModel<MyViewModel>(navBackStackEntry)
  val lifecycleOwner = LocalLifecycleOwner.current

  DisposableEffect(lifecycleOwner) {
    val observer = object: DefaultLifecycleObserver {
      override fun onStart(owner: LifecycleOwner) {
        val didTimeOut = viewModel.cancelTimeout()
        if (didTimeOut) {

      override fun onStop(owner: LifecycleOwner) {

    onDispose {
My approach as you can see, is to try popping the back stack if the timeout completed. But this leads to an exception.
Copy code
E  java.util.NoSuchElementException
E      at java.util.AbstractList$
E      at androidx.navigation.NavController.lifecycleObserver$lambda-2(NavController.kt:183)
E      at androidx.navigation.NavController.$r8$lambda$QcvT-AhOyhL9f0B2nrlZ1aMydmQ(Unknown Source:0)
E      at androidx.navigation.NavController$$ExternalSyntheticLambda0.onStateChanged(Unknown Source:2)
E      at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(
E      at androidx.lifecycle.LifecycleRegistry.forwardPass(
E      at androidx.lifecycle.LifecycleRegistry.sync(
E      at androidx.lifecycle.LifecycleRegistry.moveToState(
E      at androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent(
E      at androidx.lifecycle.ReportFragment.dispatch(
E      at androidx.lifecycle.ReportFragment$LifecycleCallbacks.onActivityPostStarted(
E      at
E      at
E      at
E      at
E      at
E      at
E      at
E      at$H.handleMessage(
E      at android.os.Handler.dispatchMessage(
E      at android.os.Looper.loop(
E      at
E      at java.lang.reflect.Method.invoke(Native Method)
E      at$
E      at
So I conclude I can’t call
like this.
Basically I am trying to “reset” this composable with a new VM. Any recommendations?