'How to notify Composition if a public property of Stable type changes?
As stated in the Jetpack compose documentation, a stable type must comply with the following contract.
- The result of equals for two instances will forever be the same for the same two instances.
- If a public property of the type changes, Composition will be notified.
- All public property types are also stable.
The first and third contracts are straightforward. How can I comply with the second point?
For example, I have a stable type called User
data class User(val username: String, var email: String)
and I change the email during the flow of the app, how can I notify the Composition?
Solution 1:[1]
Compose has a special State type that allows you to notify when a recomposition is needed. This is the most common way to initiate a recomposition.
The data class is a good tool that will give you copy for all fields out of the box, but you should avoid using var and use only val for your fields to avoid mistakes.
So, a basic example of updating a field would look like this:
var state by remember { mutableStateOf(User(username = "", email = "")) }
TextField(
value = state.username,
onValueChange = {
state = state.copy(username = it)
}
)
You can use Flow/LiveData in the same way, since they can be collected in State with collectAsState/observeAsState.
More info can be found in Compose documentation, including this youtube video which explains the basic principles.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Phil Dukhov |
