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

Md. Nazmun Sadat Khan

11/24/2021, 3:50 AM
I recently made a very simple comic viewer app for XKCD using Jetpack compose. However, my composables are too big, with lots of complicated business logic in it, launching lots of coroutines etc. I am thinking of making a custom state object inside which I am going to move all the business logic, leaving only the UI parts to the composable functions. Is it ok to launch composables from within state classes?
a

Adam Powell

11/24/2021, 4:27 AM
The phrasing of, "launch composables from within state classes" confuses me a bit, but I occasionally write state objects with suspend methods that keep updates/ongoing behavior running, and then have a composable do something like
Copy code
@Composable
fun Thing(state: ThingState) {
  LaunchedEffect(state) {
    state.keepUpdated()
  }
  // ...
}
👍 1
This tends to make unit testing
ThingState
really smooth
m

Md. Nazmun Sadat Khan

11/24/2021, 4:32 AM
My question was, to use your example, should I make
state.keepUpdated
a suspend function and launch the coroutine from the composable, or is it better to make
state.keepUpdated
a regular function and launch the coroutine inside the method.
a

Adam Powell

11/24/2021, 4:34 AM
What scope would you launch it in/where would you call the launcher method?
m

Md. Nazmun Sadat Khan

11/24/2021, 4:42 AM
Still a newbie so haven't thought about the details through, but I am currently using a
CoroutineScope
via
rememberCoroutineScope
in my composables.
a

Adam Powell

11/24/2021, 4:51 AM
Definitely don't raw launch from a
@Composable
- it's one thing if it's in a click handler or something but composables are transactional and launching is a side effect that needs to be controlled to only escape composition if composition successfully commits
This is what LaunchedEffect does for you
m

Md. Nazmun Sadat Khan

11/24/2021, 4:53 AM
It was for a click handler
👍 1
All in all, I think your approach is better. Create a custom state class, create suspend methods and let the composable decide the scope.
a

Adam Powell

11/24/2021, 5:40 AM
Yeah if you have to provide a scope to the state object things get a lot more complicated
👍 1
This sort of thing is also why things like
MutatorMutex
exist; we encountered a lot of cases where a new actor in this kind of capacity needed to be able to kick out an old one
m

Md. Nazmun Sadat Khan

11/24/2021, 5:41 AM
Ok thanks for pointing me in the right direction.
a

Adam Powell

11/24/2021, 5:42 AM
I'm not entirely sure it's the right direction yet, but I hope it's been a helpful direction to think in and I'm curious to see what you arrive at 🙂
😊 1