When you declare @Composable Function you are actually declaring a Class
Every variable that you declare inside that Function actually acts as Class Property
Every Event that you declare inside that Function (like onClick) actually acts as Class Method
This is why variable value is remembered between onClicks. Every click executes Class Method which increases Class Property. This can be seen in Console since we are not updating UI at this point (there is no recomposition taking place).
So the way that Jetpack Compose works and is being explained is totally misleading. It is explained that you work with Functions but in background they behave like Classes in order to make them stateful. So instead of using well known constructs like Classes to implement UI Views they are using Functions with a lot of magic behind the scene to make them behave stateful like Classes. Am I missing something?
//======================================================================
// MAIN ACTIVITY
//======================================================================
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Column {
MyComposable("Object1") //Create Object of Class MyComposable
MyComposable("Object2") //Create Object of Class MyComposable
}
}
}
}
//======================================================================
// MY COMPOSABLE
//======================================================================
// Instead of Function you are actually creating Object behind the scene
// So this Function actually works as Constructor for MyComposable Class
@Composable
fun MyComposable(name: String) { //CLASS
//CLASS PROPERTY
var myProperty = name
//CLASS METHOD: onClick
Text(text = myProperty, modifier = Modifier.clickable(onClick = {
myProperty += " clicked"
println(myProperty)
}))
}
Console
Object1 clicked
Object1 clicked clicked
Object2 clicked