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
snapshotFlowdoesn't know which changes to observe. When using thebykeyword,searchQuery.valueis implicitly called, and thus thesnaphotFlowcan detect the changes.To solve this, please try
or use the
bykeyword.As the official documentation remains vague about how the approaches for declaring a MutableState differ, this Reddit post summarizes the differences well.