Alexa_Gal

    Alexa_Gal

    1 year ago
    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
    @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")
        })
    
    }
    jim

    jim

    1 year ago
    Sounds like maybe it's an XY problem, what are you trying to accomplish?
    Alexa_Gal

    Alexa_Gal

    1 year ago
    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
    jim

    jim

    1 year ago
    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.
    Alexa_Gal

    Alexa_Gal

    1 year ago
    that is probably what i need, i’ll follow you advice. thanks 🙂
    Andrey Kulikov

    Andrey Kulikov

    1 year ago
    you can use a ViewModel for it. fetch the data inside a view model and get it inside the composable using viewModel()