How Compose Compiler infers stability and decide their types?
How Compose Compiler infers stability and decide their types?
Jetpack Compose uses a smart recomposition system to optimize UI updates. At the heart of this optimization is stability inference - the compiler's ability to determine whether a type's values can change over time. Understanding how the compiler reasons about stability is crucial for writing performant Compose code.
What is Stability?
In Compose, a type is considered stable if it meets these conditions:
- The result of
equals()will always return the same result for the same two instances - If a public property of the type changes, Composition will be notified
- All public properties are also stable types
Common examples:
- Stable: Primitives (
Int,String,Boolean),@Immutabledata classes, function types - Unstable: Classes with
varproperties, mutable collections (MutableList,MutableMap)
The Stability Type System
The Compose compiler uses a sophisticated type system to track stability information during compilation. This is represented by the Stability sealed class:
sealed class Stability {
class Certain(val stable: Boolean) : Stability()
class Runtime(val declaration: IrClass) : Stability()
class Unknown(val declaration: IrClass) : Stability()
class Parameter(val parameter: IrTypeParameter) : Stability()
class Combined(val elements: List<Stability>) : Stability()
}
Each variant represents a different level of certainty about stability:
1. Certain Stability
class Certain(val stable: Boolean) : Stability()
This represents types whose stability is known at compile-time with 100% certainty.
Examples:
-
Certain(stable = true):- Primitives:
Int,Long,Float,Double,Boolean,Char,Byte,Short String,Enumclasses- Function types:
() -> Unit,(Int) -> String
- Primitives:
-
Certain(stable = false):- Classes with
varproperties:data class MutableUser(var name: String) - Mutable collections:
MutableList<String>,MutableMap<String, Int> - Classes with unstable properties
- Classes with
This article continues for subscribers
Subscribe to Dove Letter for full access to 40+ deep-dive articles about Android and Kotlin development.
Become a Sponsor