Hi guys! I’m experiencing a strange behaviour. My ...
# compose
g
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
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
I’m creating it like this:
Copy code
composable(route = NavRouting.Home.destination) {
    HomeScreen(hiltViewModel())
}
m
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
Yes, I’ve placed a log and it prints 2 different instances
Copy code
init { logger.i("blah") {"$this"}}
2022-02-11 151409.683 31895-31895 I/System.out: Info: (blah) ViewModel@e40aa21 2022-02-11 151410.110 31895-31895 I/System.out: Info: (blah) ViewModel@edd1ff
r
may be the compose function which has
AnimatedNavHost
is recomposing twice
g
false alarm, my bad 😅
had a sneaky
Copy code
LaunchedEffect
doing thing it shouldn’t
✍️ 1