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

Francescos

04/28/2022, 1:51 PM
I use Navigation Compose and my usecase is to track a screen view event for each screen. Nevertheless, when I navigate from screen A to screen B and then back to screen A (which is already in the back stack), I’d like to track screen view event of screen A only once. I tried with both LaunchedEffect (Unit) and DisposableEffect (https://developer.android.com/jetpack/compose/side-effects#disposableeffect) but both of them are going to be invoked again when navigating to a screen already in the back stack. Am I missing something?
m

myanmarking

04/28/2022, 1:59 PM
that is expected i guess. I don’t know what is the proper way of solving that, but you can use rememberSaveable + boolean and track shown
or better yet, use the viewModel init block. It will only be called once
f

Francescos

04/28/2022, 2:07 PM
Thank you very much. I appreciate 👍
c

Colton Idle

04/28/2022, 4:32 PM
AFAIK if you use compose-nav, then while you navigate to different screens, your composables that go off the screen actually get thrown away (to save memory i assume?) the only "stack" that's actually there in memory still churning away is your stack of VMs. I would also do it on init{} of VM or if you want you can do this: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1630080009198100?thread_ts=1630078038.194200&cid=CJLTWPH7S which will allow you to hook into lifecycle methods, but instead of ON_RESUME or w/e you can do ON_CREATE. I also really don't want to mislead, so wait for Ian to maybe chime in?
f

Francescos

04/29/2022, 7:26 AM
Hi @Colton Idle. To be honest, I tried to listen to the ON_CREATE event (rather than ON_RESUME) when I tried the solution posted here https://developer.android.com/jetpack/compose/side-effects#disposableeffect, but ON_CREATE event is fired even when I come back to a previously opened destination. Anyway, I’ll give the solution posted by Ian Lake a try. Thank you very much
c

Colton Idle

04/29/2022, 4:03 PM
@Ian Lake sorry for the ping. But can you confirm if my above message was correct, or am I spreading the wrong info?
i

Ian Lake

04/29/2022, 10:40 PM
Even if doing it in a ViewModel init block (which is indeed only called once while the destination is on the back stack), you'll still want to make sure you use
rememberSaveable
(if doing the logging from the Compose layer) or
SavedStateHandle
(maybe the
savedStateHandle.saveable
syntax added in Lifecycle 2.5.0-beta01) to save that you've done your one time logging since even a ViewModel won't survive process death and recreation (something you can easily test with the 'Don't keep activities' developer option)
👍 1
12 Views