I’m trying to use `collectAsState` but it is resul...
# compose
g
I’m trying to use
collectAsState
but it is resulting in an infinite composition loop. When I call
collectAsState
it seems to just get the latest state and then trigger a recomposition, and then repeats that loop forever. Does anyone know what I am missing? I’m new to both technologies so it’s probably something really obvious!
If it helps:
Copy code
@Composable
fun App(component: AppComponent) {
  val authRepository = component.authRepository()
  when (val authState = authRepository.state().collectAsState().value) {
    is AuthState.Authorized -> {
      // show login flow
    }
    is AuthState.Authenticated -> {
      // show user flow
    }
  }
}
l
does
component.authRepository()
make a new instance everytime?
g
hmm maybe actually. my repo might not be a singleton, let me check!
l
I'm guessing it does. I've ran into that problem
g
yeah, that was it! I forgot to scope my repo 🤦‍♂️
👍 1
l
you could just try passing the authRepo instead of the component too
if you don't want a singleton
👍 1
g
Is there a way to detect composition loops early? I didn’t even know this was happening until i threw some logs in
t
This happened to me by accident. My UI kept refreshing in a loop, that's when I realized there was a composition loop
g
yeah i suppose it’d be more noticeable once my pages are little more fleshed out
z
I wonder how you’d distinguish a composition loop from a composable that’s being animated, which i think would look the same (new composition on every frame)
t
hmm..if there’s some state management in the animation’s progress, a composition loop might cause the animation to restart/glitch 🤔
for example, in the case of a determinate progress bar 🤔
a
as long as the actual instance returned by
authRepository.state()
does not change across calls, it won't resubscribe, it'll keep the existing subscription across recompositions
and if it does change across calls (new instance per call, for example,) then you can use
remember
with your original inputs:
Copy code
val state = remember(authRepository) { authRepository.state() }
👍 2
then you will only get a new
.state()
call if
authRepository
changes
144 Views