Reputation: 521
How to manually observe SnapshotStateList or MutableState? It said that mutableStateListOf returns list that can be observed, but I can't find such method. Is it true that only Compose can observe changes?
Upvotes: 3
Views: 5395
Reputation: 29615
The easiest way to observe of a state object, such as the result of mutableStateOf
or mutableStateListOf()
, is by using snapshotFlow
.
snapshotFlow
's block
parameter will be called when any state object it uses has been changed and the result of block
will be emitted to the flow such as snapshotFlow { snapshotList.toList() }
. Note the toList()
is required here otherwise the snapshotList
itself is used which the snapshotFlow
doesn't consider changed (it is always the same instance) so it will only emit once. In compose runtime version 1.4, toList()
was changed so that calling toList()
on a SnapshotStateList
does not perform a copy.
Alternately, you can use SnapshotStateObserver
which enables multiplexing a single apply observer to observe a multitude of lambdas. This is what Compose UI layout and draw use, for example, to track when to recalculate the layout and when to replay drawing commands.
State objects do not have an observe
or subscribe
equivalent because Snapshots
was designed and optimized to observe an open, dynamic set of objects read by a function and any function it calls (such as Compose needs); and no fast path for a single object (which Compose does not need) was implemented and is therefore expensive. Having an observe
method of a state object would imply it is fast and cheap, which it is not.
Upvotes: 4