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

manueldidonna

08/25/2020, 10:34 PM
Trying to change a state in the background, sometimes I get the following error "Reading a state that was created after the snapshot was taken or in a snapshot that has not yet been applied".
Copy code
// fetch all the items when the inventory change
    launchInComposition(inventory) {
        val currentInventory = inventory.value
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            // fetchAllItems() update the state
            currentInventory.fetchAllItems()
        }
    }
j

jim

08/25/2020, 10:35 PM
cc @Chuck Jazdzewski [G]
c

Chuck Jazdzewski [G]

08/26/2020, 5:08 PM
Can you file a bug with a repo case?
z

Zach Klippenstein (he/him) [MOD]

08/26/2020, 8:06 PM
@manueldidonna Did you file a bug for this? I’ve got another snapshot bug happening with subcompositions, I don’t think it’s related but i’d like to follow this bug as well.
c

Chuck Jazdzewski [G]

08/26/2020, 8:07 PM
The above code does not give me enough context to determine why this is happening. The reason this would happen is if
inventory
is accessed before the snapshot it was created in is applied. Maybe @Adam Powell can give more context on what snapshot
launchInComposition
should be running in.
a

Adam Powell

08/26/2020, 8:08 PM
it launches undispatched when we run composition lifecycle observers and runs as a child job of the recomposer's compose and apply loop
so until first suspend it should be identical to running in an
onCommit
after that it'll be on the AndroidUiDispatcher if you're using defaults
after switching to the IO dispatcher I presume everything is as per normal when working with snapshots off the main thread
launchInComposition
doesn't do anything special to try to propagate a current snapshot through the CoroutineContext
the intent is that
launchInComposition
does not have an opinion on this
I would expect that in the IO dispatcher block it's working with the current global snapshot
m

manueldidonna

08/26/2020, 8:22 PM
I can file a bug If it's still needed @Chuck Jazdzewski [G]
c

Chuck Jazdzewski [G]

08/26/2020, 8:22 PM
That would help as I need more context to determine what is going wrong here.
👍🏻 1
m

manueldidonna

08/26/2020, 9:23 PM
https://issuetracker.google.com/u/1/issues/166486000 I hope this report is useful enough
c

Chuck Jazdzewski [G]

08/28/2020, 12:58 AM
Thanks for the report! I replied in the report with a work-around you can use now. We are discussing how the above should work. Your code should work as written. However, now,
withContext(<http://Dispachers.IO|Dispachers.IO>)
does not ensure it runs after the composition snapshot has been applied which could cause this code to fail. The work-around prevents the
withContext
from executing until after composition's snapshot has applied.
2 Views