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

grandstaish

06/12/2020, 8:20 PM
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

Luca

06/12/2020, 8:22 PM
does
component.authRepository()
make a new instance everytime?
g

grandstaish

06/12/2020, 8:22 PM
hmm maybe actually. my repo might not be a singleton, let me check!
l

Luca

06/12/2020, 8:24 PM
I'm guessing it does. I've ran into that problem
g

grandstaish

06/12/2020, 8:25 PM
yeah, that was it! I forgot to scope my repo 🤦‍♂️
👍 1
l

Luca

06/12/2020, 8:25 PM
you could just try passing the authRepo instead of the component too
if you don't want a singleton
👍 1
g

grandstaish

06/12/2020, 8:28 PM
Is there a way to detect composition loops early? I didn’t even know this was happening until i threw some logs in
t

Tash

06/12/2020, 8:30 PM
This happened to me by accident. My UI kept refreshing in a loop, that's when I realized there was a composition loop
g

grandstaish

06/12/2020, 8:31 PM
yeah i suppose it’d be more noticeable once my pages are little more fleshed out
z

Zach Klippenstein (he/him) [MOD]

06/12/2020, 9:09 PM
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

Tash

06/12/2020, 9:12 PM
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

Adam Powell

06/12/2020, 9:23 PM
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
73 Views