Lifecycle observer in Compose

SeongUg Steve Jung
2 min readJul 5, 2021

--

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

  1. In very first time, The function will run name show Text() .
  2. Somehow, Let’s say thatisName is changed to false
  3. Composer will do recomposition. Then it will run imageRes and show Image()

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.

  1. In very first time, FooViewModel will be run and fetch name
  2. Somehow let’s say isName is changed to false
  3. Then BarViewModel will be run and fetch imageRes

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

--

--

SeongUg Steve Jung
SeongUg Steve Jung

Written by SeongUg Steve Jung

Android Developer, Google Developers Experts

No responses yet