https://kotlinlang.org logo
#compose
Title
# compose
a

Alexa_Gal

01/30/2021, 1:55 AM
is there any way to run a function that will be executed only in the first composition . Compose A compose and prints a
Hello word
Compose A navigates to Component B Component B popsBack to Component A Component A should not print again “Hello word” since this was already on the stack
Copy code
@Composable
fun ComponentA() {

    LaunchedEffect(Unit) {
        Log.e("=======", "I need to run only once and not when other Component PopsBack")
    }

    Button("Continue", onClick = {
        navController.navigate("ComponentB")
    })

}
j

jim

01/30/2021, 1:56 AM
Sounds like maybe it's an XY problem, what are you trying to accomplish?
a

Alexa_Gal

01/30/2021, 2:00 AM
In the ComponentA in the first composition i would like to fetch some data and track the screen and after some time user will navigate to a ComponentB or ComponentC depending of the data i get from this screen. I would like to do the request only once and the tracking and not when componentB or componentC popBack
j

jim

01/30/2021, 2:05 AM
I would suggest that your A is not being a functional transform of data->UI, and is instead trying to do way too much. As a general rule of thumb, having widgets which fetch data or maintain state is a code smell, and it sounds like your widget is trying to do both. You would probably be better of hoisting the data fetch up to the activity level, and pass it down to A, B, and/or C. This would also happen to solve the problem of not over fetching, since now the data is being fetched and maintained outside of the composables.
a

Alexa_Gal

01/30/2021, 2:08 AM
that is probably what i need, i’ll follow you advice. thanks 🙂
a

Andrey Kulikov

01/30/2021, 1:49 PM
you can use a ViewModel for it. fetch the data inside a view model and get it inside the composable using viewModel()
2 Views