Jetpack Compose — Where is recomposed?
After I published my last post Jetpack Compose - One-time request, I came up with a question if it works in any condition. SharedFlow doesn't persist value inside of it so I expected it would work as a one-time request from ViewModel to Composable Views. However, I wondered if the collected flow would be consumed whenever recomposition is triggered.
I posted an article about using SharedFlow with Jetpack Compose. But I think `collectAsState()` doesn't work because it holds the value as state, as it says. Then it doesn't work as a one-time request 🤔 I need to investigate ithttps://t.co/GKjzJfXaZE
— Masa (@alpaca0984) August 15, 2022
I prepared a sample code. If the update
block of the AndroidView is evaluated every time I hit the Button, the SharedFlow won't work as a one-time request.
And the result is that hitting the Button and updating count
variable doesn't affect the update
block. It's evaluated only when the url
variable is updated. So, as a conclusion, we can use SharedFlow as one-time requests because it is consumed by Views only when ViewModel emits a new value 🎉
Let's look into the AndroidView()
deeply. This is how it looks.
The update
block is passed to set()
function which is impleted as:
So what it essentially does is that AndroidView remembers (something like taking a snapshot) of the update
block. And if it changes during the recomposition, it evaluates the block. And it's not only for AndroidView, of course. Jetpack Compose recomposes UI only where changed.
It reminds me of the Virtual DOM in React. React keeps the DOM structure in memory, and when something changed, it builds the latest DOM structure in memory as well. And with the diffing algorithm, it updates the actual DOM where only needs to be updated. I guess Jetpack Compose does similar things.
After the investigation, I found that it's clearly described in the official doc as:
The Compose framework can intelligently recompose only the components that changed.
Here is the page 😆
When you wonder about something, the first thing you should do is to check out the official doc. But replicating it by yourself and digging into that makes you understand it deeply!
Happy coding!