Home > OS >  Wait for Coroutine execution before updating UI
Wait for Coroutine execution before updating UI

Time:08-26

I'm making an app uisng Jetpack Compose where i have a composable function that loads some data from a FireStore db and then calls another composable function with the results.

in terms of code, to give an idea, it's something like this:

@Composable
fun mainScreen(myData: MutableState<myObject?>)

coroutineScope.launch {
        // loadData() updates a component of mydata, mydata.list which contains a List<String> 
        viewModel.loadData()
                    }
    // load second screen with updated data
    secondScreen(myData)
}

Actually secondScreen() gets launched BEFORE coroutine ends because obviously coroutines execute async tasks.

What can i do to call secondScreen AFTER coroutine ends?

Thank you!

CodePudding user response:

There are a couple of major problems with this.

The first is that you will launch that coroutine and call loadData every time this screen recomposes.

Instead you probably want to put this logic in a call to LaunchEffect.

Second is you probably don't want to pass the state into secondScreen but instead the values.

This is assuming the viewModel holds the state.

@Composable MainScreen() {
   // replace 0 with something that indicates when the data should be loaded again, that this screen could observer through a state.
   LaunchEffect(0) {
      viewModel.loadData()
   }

   val data = viewModel.state.value
   if (data != null) {
       SecondScreen(data)
   }
}
  • Related