Home > database >  Is there a better way to update text in jetpack compose?
Is there a better way to update text in jetpack compose?

Time:09-28

Is there a better way to update the text value here by the value from the database?

@Composable
private fun DisplayShops() {
var shopid by remember { mutableStateOf("")}
SideEffect {
    val value = GlobalScope.async {
        val res = withContext(Dispatchers.Default) {
            getDbData() // this gets the database data
            delay(1000)
            shopid=shop_id// the shop_id is variable defined in the activity and it has the value retrieved from the database
        }
    }
}
Text(text =shopid)
    }

CodePudding user response:

That's not a good solution for 2 reasons:

  • the code will run at each recomposition, because you are using SideEffect, you probably want to use LaunchedEffect instead
  • placing your business logic in your composables is not the right solution, makes your composables tightly coupled to your business layer and hard to test

You should consider creating a ViewModel that will fetch the data from the database and then expose the value you want to display from the ViewMOdel using a MutableState object that you can then observe in your composable.

You can read this for more details.

  • Related