https://kotlinlang.org logo
Title
g

Guilherme Delgado

02/11/2022, 12:03 PM
Hi guys! I’m experiencing a strange behaviour. My ViewModel
init {}
it’s called twice. I’m using jetpack compose (1.1.0 and it happened also with 1.1.0-rc01): • ActivityA has ViewModelA and everything is ok. • ActivityB has a
AnimatedNavHost
with 3 composable (“screens”). When they’re first created I get this 2 time problem, but after that, when I change between them, the
init {}
is called only once as expected. What could it be?
m

Marcello Galhardo

02/11/2022, 2:31 PM
Hm. Are you sure it is the same ViewModel instance? I would guess your code is, for some reason, creating N instances of the ViewModel and that is why you are getting the
init
method called twice.
g

Guilherme Delgado

02/11/2022, 2:49 PM
I’m creating it like this:
composable(route = NavRouting.Home.destination) {
    HomeScreen(hiltViewModel())
}
m

Marcello Galhardo

02/11/2022, 2:55 PM
I don’t use Hilt but it looks like it should be working fine. Can you place a breakpoint inside your
init
method and reproduce the “call init twice” and ensure the
this
instance is exactly the same? (If you don’t know how to do it, see my picture below: the value after
@
should tell you if the instances are the same or not).
g

Guilherme Delgado

02/11/2022, 3:09 PM
Yes, I’ve placed a log and it prints 2 different instances
init { logger.i("blah") {"$this"}}
2022-02-11 15:14:09.683 31895-31895 I/System.out: Info: (blah) ViewModel@e40aa21 2022-02-11 15:14:10.110 31895-31895 I/System.out: Info: (blah) ViewModel@edd1ff
r

Ravi

02/11/2022, 5:01 PM
may be the compose function which has
AnimatedNavHost
is recomposing twice
g

Guilherme Delgado

02/11/2022, 6:19 PM
false alarm, my bad 😅
had a sneaky
LaunchedEffect
doing thing it shouldn’t
✍️ 1