https://kotlinlang.org logo
#compose
Title
# compose
f

Filip Wiesner

01/22/2022, 6:32 PM
So I was reading through the Compose runtime code and while looking at
withMutableSnapshot
(which has been mentioned here several times) I saw a little note at the end of the doucmentation:
[block] must not suspend if [withMutableSnapshot] is called from a suspend function.
Why is that? 🤔 Is it because other code can be run on the same thread when the
block
suspends resulting in other unrelated part of the app being in this snapshot? I am not sure I know enough about Compose and Coroutines to be sure.
a

Adam Powell

01/22/2022, 7:07 PM
Yes, it's driven by a form of ThreadLocal and we don't have a wiring from this API to a CoroutineContext-based management of it
Any time we've looked at addressing this we confront the idea that the longer you leave a snapshot outstanding without committing it, the more likely it is that attempting to commit it can cause a conflict or involve out of date inputs that were frozen in time
If you do need to take a snapshot and send it to another thread to do some work with it, you can do it with the lower level
enter
API
f

Filip Wiesner

01/22/2022, 7:23 PM
I see, thanks for the quick response 👌 So would this be OK? (even though it doesn't really make sense)
Copy code
var state by mutableStateOf(0)
val snap = Snapshot.takeMutableSnapshot()

snap.enter { state = 1 }

val result = suspendWhileGettingNumber()

snap.enter { 
    if (result > 5) state = result
}

snap.apply()
a

Adam Powell

01/22/2022, 8:35 PM
Yes, that general pattern will work fine
You'll also want to make sure you dispose it in a finally
👍 1
Snapshots will leak resources if not disposed
6 Views