Abstract

If you have touched Flutter, you know what a state is like. For example, if you are not familiar with Compose, you may be confused by some concepts. But it’s also something we’re familiar with, just in a different way. For example, what I understand is that data corresponds to state and combination corresponds to interface. Although some of their basic knowledge and interaction modes are different, it does not affect my initial learning Compose.

In the View hierarchy of Android, the interface is built one View after another, such as LinearLayout and TextView. We modify it by finding the reference of the View and setting its internal state, such as setting the text of TextView. Jetpack Compose is a new declarative toolkit for Android, so how composition and state can work together once they are decoupled. Or simply, in Compose, how do I update the Text of a Text?

Three concepts

For composing, I think we should understand three concepts: composition, state and event. Composition is used to describe the interface generated by runnable composition items. Composition is a tree structure that describes the composable items of an interface. A state in an application is any value that can change over time. Such as animation, network request after the data. Events are generated by users or programs, such as click events. In Compose, the state is separated from the event, where the state represents a value that can be changed, and the event represents a notification that something has happened. Separating state from events decouples the presentation of state from how it is stored and changed.

val count= remember{ mutableStateOf(0) }

Column() {
    Button(onClick = { count.value++ }) {
    }
    Text(text = "${count.value}")}Copy the code

In the above code, after the click-through status is decoupled from the click event, the click-through number can be shown separately, and the click-through status display of the Text Text is decoupled from its change mode.

Remeber can be used to store individual objects, and the system stores the values calculated by Remember during the initial period and returns the stored values during reorganization. Storage objects can be mutable or immutable.

State storage and change

When a mutable object is stored with Remember, internal state is added to the composable item. For example, set a separate state for Text in the previous section. The mutableStateOf function creates an observable MutableState

object, which is the observable type of the Compose runtime integration, as well as its parent interface State

. Compose recommends making the state observable so that when the state changes, Compose can automatically reorganize the interface.

In addition to ‘MutableState’ to store state, we can also use familiar LiveData,Flow,RxJava.

val liveData= MutableLiveData<String>()
val text by liveData.observeAsState()
Copy the code

The observeAsState function is an extension of LiveData and converts a LiveData object into a State object.

Flow

val value: String by stateFlow.collectAsState()
Copy the code

RxJava

val completed by completable.subscribeAsState()
Copy the code

Compose extends functions to convert existing framework observable classes into State

objects that can be read by composable functions, so we can convert our own observable classes into State

objects using the extension function.

If need to manually trigger the restructuring, such as in the case of getting data from the server, by using currentRecomposeScope. Invalidate ().

Elevation of state

Promotion of state refers to a pattern of moving state to callers of composable items to make composable items stateless. One is that the caller can modify the composite item through state, rather than just calling the composite item itself. Second, different combinations can reuse the same state.

State promotion usually involves replacing the state variable with two parameters:

  • Value: T: current value to be displayed
  • onValueChange: (T) -> Unit: The event that requests a value changeTIs the recommended new value.

restructuring

During the initial composition, Jetpack Compose tracks the composable items that you call to describe the interface in the composition. Jetpack Compose then arranges a reorganization when the state of the application changes. Composable items that may have changed are run during reorganization in response to state changes, and Jetpack Compose updates the composition to reflect any changes.

Regroup to refresh widgets in the interface tree whose state has changed. Recombination is intelligent, and the system redraws widgets with new data as needed, while widgets that do not depend on new data are not redrawn.

In Compose programming, note the following as well:

  • Composable functions can be executed in any order. This means that procedural order consistency does not exist in composable functions, so you cannot set a global variable in the Compose composable function, but on their caller.

    Column() {
        Text(text = "I am Text1")
        Text(text = "I am Text2")
        Text(text = "I am Text3")}Copy the code

    For example, the three texts here do not necessarily call Text1, then Text2, and then Text3; they may be called out of order. But they end up in the same order as columns, from top to bottom.

  • Composable functions can be executed concurrently. That means Compose can take advantage of CPU’s multi-core capabilities to optimize recombination by running composable functions in parallel.

  • Regrouping skips as much as possible. Compose tries to regroup only the parts that need to be updated, which means skipping as many composable items as possible. Each combinable function and lambda can reassemble itself.

  • Composable functions can be run very frequently

    In some cases, you might run a composable function for each frame of the interface animation. If you perform expensive operations (such as a network request, reading data from a file) on a modified composite function, the interface can get stuck. So you should move expensive operations to other threads and pass data to composable functions via ViewModel or LiveData.

The last

This article is based on the study of the status and combination of official documents. At the same time, due to the upgrade of the version, some information has been changed, so we need to refer to the document to update the record

Welcome to like + follow + comment triple play

【Github】【 Nuggets 】【 blog 】