I recently made a very simple comic viewer app for...
# compose
m
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
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
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
What scope would you launch it in/where would you call the launcher method?
m
Still a newbie so haven't thought about the details through, but I am currently using a
CoroutineScope
via
rememberCoroutineScope
in my composables.
a
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
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
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
Ok thanks for pointing me in the right direction.
a
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