nglauber
08/20/2021, 3:09 PMScreenA
which I’m using
LaunchEffect(viewModel) {
viewModel.loadSomeData()
}
In this screen, somewhere in the future I call ScreenB
. But when I go back to ScreenA
, the loadSomeData()
is called again…
Is there a way to avoid that?Luke
08/20/2021, 3:33 PMnglauber
08/20/2021, 3:37 PMonCreate
method.KamilH
08/20/2021, 3:39 PMAdam Powell
08/20/2021, 5:06 PMprivate val alreadyLoaded = false
fun loadSomeData() {
if (alreadyLoaded) return
// ...
alreadyLoaded = true
}
With activities and fragments you still get multiple onCreates too under the same circumstances and need to take the same approach if you really want it to only happen once.nglauber
08/20/2021, 5:08 PMnglauber
08/20/2021, 5:09 PMonCreate
because it will not be called again when I go back to it.Nabeel
08/20/2021, 5:47 PMinit{}
function solves the issue?nglauber
08/20/2021, 6:01 PMForm
, I set the data.
Then, when I navigate to Country
to update the country field in Form
the setMyData
is called again and reset the data… 😕nglauber
08/20/2021, 6:23 PMmyData
set to Form
is loaded in Home
.
So, when I close the Form
and go back to Home
, the data is loaded again 😞Ian Lake
08/20/2021, 11:39 PMinit
blocknglauber
08/20/2021, 11:43 PMinit
, because HomeViewModel
load some data and it needs to pass some of this data to the FormViewModel
just once.nglauber
08/20/2021, 11:45 PMprivate mydata: MyData? = null
fun setMyData(d: MyData) {
if (myData == null) {
mydata = d
}
}
Ian Lake
08/21/2021, 12:12 AMnglauber
08/21/2021, 3:17 AMIan Lake
08/21/2021, 3:23 AMnglauber
08/21/2021, 3:34 AMHomeViewModel
requests the data to be loaded (which is cached by the repository)
• In the FormViewModel
, in the init
block, I asked for the data again (which cached) and call setMyData
That was it… An elegant solution 🙂Ian Lake
08/21/2021, 4:09 AMShakil Karim
08/21/2021, 11:38 AM