When using `collectAsState` extension function on ...
# compose
c
When using
collectAsState
extension function on a flow... should I be
remembering { }
the initialValue? i.e. I have something like this
myflow.collectAsState(initial = runBlocking { a value I NEED to calculate for initial state})
I understand (and am okay with the delay in my main thread, but I want to make sure that the call to initial will only be called... initially 😅
f
> should I be
remembering { }
the initialValue? No, it's just the initial state of mutable state. If you look into implementation, the value is used like this:
Copy code
val result = remember { mutableStateOf(initialValue) }
🙌 1
Also, consider using
StateFlow
instead of
Flow
if possible
c
I know someone will inevitably say that I should not have run blocking in my
inital
but... I'm using a webview and the value being calculated is the base url. so if i don't wait, then i basically get two loads of the webview, because it'll try to load an actual default like empty string, and then it'll go ahead and reload with the new url it pulls from shared prefs/calculates. moving to this route has removed a flash in the webview so im going to move forward in this route
thanks @Filip Wiesner
f
> I'm using a webview and the value being calculated is the base url. so if i don't wait, then i basically get two loads Why not just display the WebView after you know the url instead of blocking the main thread?
Copy code
if (baseUrl != null) WebView(baseUrl)
else ProgressBar()
I just hope the calculation is not some network call kodee frightened
c
I'm considering that as well, but my designer doesn't like the flash of the progress bar. lol. but yes it is not a network call. it happens really fast, but just happens to be suspending.
f
You can do just
if (baseUrl != null) WebView(baseUrl)
if you don't want the progress bar 😄 But fair enough. Just know what you are doing and hope that the underlying computation won't change to something more heavy in the future.
runBlocking
is a dangerous tool
K 1
s
I have something like this
myflow.collectAsState(initial = runBlocking { a value I NEED to calculate for initial state})
If your code actually looks like this then you'll need to remember the initial value
https://kotlinlang.slack.com/archives/CJLTWPH7S/p1704284717492659?thread_ts=1704284148.963969&cid=CJLTWPH7S The value is indeed used only once by the remember lambda but it'll be evaluated on every composition because you're passing it as a parameter to the
collectAsState
function
remembering the initial value would not have been needed if
initialValue
param was also a lambda
f
Yeah, true. Didn't think of that, sorry kodee sad