Not really sure where this question should go. It'...
# compose-android
c
Not really sure where this question should go. It's part compose/part threading/part coroutines. But I'm putting it here. Essentially I have a method in my viewModel that's called
fun loadData()
which hits the network then comes back and updates compose snapshot state. Works fine. Cool. Typically loadData is called from a LaunchedEffect. BUT. Now I'm using a 3rd party sdk where it takes a lambda for initialization completion and so I want to move away from the LaunchedEffect and over to the sdk completion listener. So basically I call
sdk.init( { viewModel.loadData() } )
. Cool. Everything still seems to work fine. If I call loadData based on a compose launchedEffect and put a
log
in
loadData()
for
Thread.current().name
I get
main
. BUT after using the
sdk.init()
and passing the lamda in, I get a different thread entirely. Should I be worried about updating my compose snapshot state from
Thread-29
(or w/e) instead of
thread main
?
m
I guess a safer bet here would be to update your snapshot state using
Snapshot.withMutableSnapshot { ... }
only if you're not on the main thread, https://kotlinlang.slack.com/archives/CJLTWPH7S/p1697173952963309?thread_ts=1697145056.766169&cid=CJLTWPH7S
s
you can convert your callback to a suspend function using:
suspendCoroutine
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/suspend-coroutine.html then you end up with
Copy code
suspend fun initAndLoadData() {
    sdk.awaitInit() // uses suspendCoroutine to convert from callback to suspend
    loadData()
}
z
Updating state from another thread is fine. If you’re updating more than a single state object, you may want to consider the above suggestion of using
withMutableSnapshot
to ensure all updates are seen by the main thread at the same time
👍 1
c
Updating state from another thread is fine
Cool. Is there a doc that points to that by any chance? Would like to share with my team vs just saying "Zach K says O.K." 😅
z
hm looking for it, found this at least 😅 https://issuetracker.google.com/234475017
c
Thank you!