Hello! I am having troubles understanding how `rem...
# compose
g
Hello! I am having troubles understanding how
remember
works, so I created this simple example. Here, every time I click on
Switch
I get a new random number. AFAIU this happens because
remember
gets removed from the tree, so it forgets the value it remembered. How can I get around it? I need something similar to the
View.GONE
that doesn't remove the node from the tree, but makes it non interactable.
s
Yeah you got it. When it leaves the tree completely, it can't still be remembered across compositions. If you want it to persist, you must have it in a place where it does not leave the tree. So just extract it to right above the
if (bool)
line. So:
Copy code
val text = remember { Random...}
if (bool) {
  Text(text = text)
} else {
  Text(text = text)
}
This would persist the text across recompositions, and even if bool changes back and forth
g
Yes, I can extract, but it was just the simplest example I can provide. Here is the more complex version. WebView gets reloaded every time I switch destination. This is what I am trying to avoid
s
Heh, we went from a simple example to the nuclear one quite quickly 😅 This reminded me of this thread https://kotlinlang.slack.com/archives/C04TPPEQKEJ/p1709791721938469 but I still feel like I don't have an answer for this myself. I haven't used WebView myself so I've been lucky to avoid this issue 😄
g
This question is not about
WebView
itself. I just used it so you cannot "cheat your way out" by extracting
remember
function 🙂 I just want to understand, can I remove a node from the tree without reseting
remember
or
AndroidView
🚫 1
k
in that case you have to extract required state outside of the UI. as I remember there is a webview client which can be declared externaly
g
@Konstantin Tskhovrebov So, I have to use correctly scoped
ViewModels
so store the state. But what about
Views
themselves? They are not cheap to create. Should I implement my own view pool then?
k
It depends on you case. It is not typical scenario to use android views in compose scenes. So, if you want achieve a high performance in the case of show/hide android views then, I guess, yes, you may try to implement some caches
m
You might be interested in reading this thread: https://kotlinlang.slack.com/archives/C01D6HTPATV/p1719423595969549?thread_ts=1719415671.383299&cid=C01D6HTPATV
TL;DR
use
SaveableStateHolder
which being utilized by most navigation libraries under the hood to save state for destinations that aren't currently visible but still exist on the backstack
s
In the
WebView
case you could also try
movableContentOf
to preserve the state, but it can get funky when view gets involved.
t
Sounds similar to my issue 😄 https://kotlinlang.slack.com/archives/CJLTWPH7S/p1709132135571379 I have not gotten around to it yet, but my plan was to keep a reference to it in the hosting activity and clean it up when the activity is destroyed