In my application, I added animations anytime we navigate to another screen:
NavHost(
navController = navController,
startDestination = startDestination,
enterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(TRANSITION_ANIMATION_DURATION)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(TRANSITION_ANIMATION_DURATION)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(TRANSITION_ANIMATION_DURATION)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(TRANSITION_ANIMATION_DURATION)
)
}
) {
composable(route = AppDestination.Recent.destination) { nav ->
AbcRoute(navController = navController, entry = nav)
}
}
And in the route:
@Composable
fun AbcRoute(
navController: NavController,
entry: NavBackStackEntry,
) {
val objectA = entry.arguments?.getString(AppDestination.Abc.objectA)?.let {
Json.decodeFromString<A>(it)
} ?: return
val viewModel = hiltViewModel<AbcViewModel>()
val lifecycle = LocalLifecycleOwner.current.lifecycle
val state = viewModel.enhanceState.collectAsStateWithLifecycle()
LaunchedEffect(lifecycle) {
viewModel.initialize(objectA)
}
In ViewModel, I start to call API every time the user opens the screen. But the problem is, because it have animation so the screen recompose many time -> recall API many times.
- I added the request to ViewModel scope and it cancels but sometimes the call still succeeds, and it does not look like a good idea. Do we have the right approach for this?
Thanks!
I see you're using
lifecycle
as your key to theLaunchedEffect
. Most of the time if I want to only execute a piece of code once in compose I useLaunchedEffect(Unit){}