I have a situation with the snapshotFlow recently when trying to observe changes from a MutableState. Here is the snippet
val searchQuery = mutableStateOf("")
snapshotFlow { searchQuery }.collectLatest {
}
But when the searchQuery
changed, there was nothing happened in collectLatest
block. It seems the snapshotFlow
not find any changes from searchQuery
. I guessed. Then I changed the searchQuery declare to var searchQuery by mutableStateOf("")
. The snapshotFlow works as expected. Can anyone explain me why? Really appreciate!
Please refer to this StackOverflow answer:
With your current approach, the
snapshotFlow
doesn't know which changes to observe. When using theby
keyword,searchQuery.value
is implicitly called, and thus thesnaphotFlow
can detect the changes.To solve this, please try
or use the
by
keyword.As the official documentation remains vague about how the approaches for declaring a MutableState differ, this Reddit post summarizes the differences well.