How can I call a function just once even if there’...
# compose
t
How can I call a function just once even if there’s configuration changes?
c
By function, do you mean composable? If so, just don't change the backing state?
t
I want that when the composable shows it calls a
fetch()
in the view model, but just the first time
s
you might be after disposable effect
j
Don't trigger the
fetch
logic from the UI layer, e.g. in your init method of your
ViewModel
☝️ 1
t
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
+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
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
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
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
Thanks for the link @josefdolezal! I’ll take a look 🙂