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

Tgo1014

12/06/2021, 4:01 PM
How can I call a function just once even if there’s configuration changes?
c

Colton Idle

12/06/2021, 4:01 PM
By function, do you mean composable? If so, just don't change the backing state?
t

Tgo1014

12/06/2021, 4:04 PM
I want that when the composable shows it calls a
fetch()
in the view model, but just the first time
s

Suser

12/06/2021, 4:09 PM
you might be after disposable effect
j

jannis

12/06/2021, 4:09 PM
Don't trigger the
fetch
logic from the UI layer, e.g. in your init method of your
ViewModel
☝️ 1
t

Tgo1014

12/06/2021, 4:11 PM
Hmm I guess makes sense, I’m having some issues on testing because sometimes the initial state is not working properly, so that’s why I was thinking about removing the
init{}
from it, so I guess ideally I should fix it 😅
a

Adam Powell

12/06/2021, 4:15 PM
+1 to the idea that this policy is probably better implemented at the ViewModel layer or your data layer that the ViewModel provides access to
c

Casey Brooks

12/06/2021, 4:17 PM
Ideally, the function itself shouldn't care about the logic at all. The VM produces some state, and you pass that state into the Composable function. Testing should be just trivially re-creating that state object and passing it in without the VM
t

Tgo1014

12/06/2021, 4:19 PM
I guess the problem is some racing condition that I can’t find, it sometimes work and sometimes doesn’t so I’m going crazy to understand, but that’s not related to compose 😅
j

josefdolezal

12/07/2021, 8:53 AM
there was a really good thread about this issue exactly.. the problem with vm’s
init
is that it’s actually not connected to composable’s lifecycle. my preference is to use flows instead
t

Tgo1014

12/07/2021, 8:57 AM
Thanks for the link @josefdolezal! I’ll take a look 🙂