Lifecycle observer in Compose
Migration Rule 3 : combine Activity Lifecycle with Compose
As beginning of this series, We have our own lifecycle handler. We also using lifecycle observer but with special flavors.
(I would skip introduction of our lifecycle handler.)
In Compose, it has its own lifecycle : Composition & Re-composition.
It simply can be described : Composer will run @Composable
functions while focused.
for example, Let’s below code
- In very first time, The function will run
name
showText()
. - Somehow, Let’s say that
isName
is changed tofalse
- Composer will do recomposition. Then it will run
imageRes
and showImage()
In case #3 from #1, name
state is meaningless. So Composer
will dispose name
Likely, if our custom lifecycle handler is in if-else statements
, one of statements wouldn’t be needed to run.
To prepare lifecycle handler, I created our own LocalComposotionProvider
of lifecycle-handler.
We set this in top of @Composable
Via LocalLifecycleHandler.current
, We are going to access our own lifecycle handler like this when it need to listen activity lifecycle.
Eventually, We can activate lifecycle observer for our custom lifecycle handler when it is needed.
- In very first time,
FooViewModel
will be run and fetchname
- Somehow let’s say
isName
is changed tofalse
- Then
BarViewModel
will be run and fetchimageRes
From #1 to #3, FooViewModel
was run. In that time, FooViewModel will be observing our lifecycle handler. But after change of isName
, FooViewModel
will be disposed by Composer and BarViewModel
will be run and observe life cycle handler
Conclusion
Keep in mind about Side-Effect
of Compose. DisposableEffect
will let you know when Composer activates or deactivates your state.
Migration Rule 4 : Compose Navigation without Hilt and ViewModelProvider