Composable function lifecycle

Kururu
3 min readDec 1, 2022

--

jetpack compose is modern UI toolkit for android . is a declarative UI which replace the Imperative one (xml).

in classic way you use to handle many activity or fragment lifecycle.( onStart , onCreate, onResume …etc)

according to official docs:

The lifecycle of a composable is defined by the following events: entering the Composition, getting recomposed 0 or more times, and leaving the Composition.

so we have three event:

I. Enter Composition

II . Getting recompose for N times

III. leaving composition

A Composition can only be produced by an initial composition and updated by recomposition. The only way to modify a Composition is through recomposition.

for example:

@Composable
fun MoviesScreen(movies: List<Movie>) {
Column {
for (movie in movies) {
key(movie.id) { // Unique ID for this movie
MovieOverview(movie)
}
}
}
}

in this way to update the list we recall compose function with an updated list.

otherwise ,we have to handle recoposition without need to recall function .

If a composable is already in the Composition, it can skip recomposition if all the inputs are stable and haven’t changed.

so how to do Recomposition?

recompositon depends on the composable function variables type

if variables are from stable types((Boolean, Int, Long, Float, Char, etc) then no recomposition will happen.

so then how to convert these stable types in such type that can lead to recomposition?

well , according to official docs:

Composable functions can use the remember API to store an object in memory. A value computed by remember is stored in the Composition during initial composition, and the stored value is returned during recomposition. remember can be used to store both mutable and immutable objects.

so we have to MutableState<T> interface to add mutability to our compose function so recomposition will happen every time the value of this type changes.

the MutableState<T> class if frome type State<T>

interface MutableState<T> : State<T> {
override var value: T
}

to create a variable of this type there are many helpers you can use:

mutableStateOf

var list by remeber{mutableStateOf(initialValue)}
or
val list = remember { mutableStateOf(initialValue) } // val variable will not change

The by delegate syntax requires the following imports:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

then to update this value you can use:

list.value = ….

recomposition happen when you update the value that of type MutableState<T>

there are other types of State other Than State<T> or MutableState<T> , compose also support the following:

these also can update the state and lead to recomposition

thanks for reading :)

references:

--

--