当前位置:网站首页>Compose programming idea

Compose programming idea

2022-06-21 17:40:00 Lighthouse @kuaidao

Preface

compose I've been familiar with it for weeks , follow google sample When understanding , How to declare the parameter list of composable functions , Event up , There is still a deviation in the understanding of data transmission downward . Re understand compose Programming idea

1. Early based View Number of micro pieces :

Update the interface : Multiple need to be updated at the same time View, Will miss . complex View Widget update will update the status of previously removed widgets

2. Declarative paradigm :

tips:mvvm Data driven interface ui to update . Interface (Fragment,Activity) subscribe ViewModel Medium LiveData, Notify the interface to refresh when the data changes . and lifecycle Series of auxiliary management classes introduced to avoid subscription memory leakage .

compose: A declarative interface framework ,【 Completely regenerate a screen 】

Declarative paradigm shift

View Number of micro pieces : In many object-oriented imperative interface toolkits , You can initialize the interface by instantiating the widget tree . You usually use Inflate XML Layout file to achieve this . Each widget maintains its own internal state , And to provide getter and setter Method , Allow application logic to interact with widgets .

Compose In the declarative method of : The widget is relatively stateless , And don't offer setter or getter function , Widgets are not provided as objects , You can update the interface by calling the same composable function with different parameters

Interface description : From top to bottom
 Insert picture description here

Application logic provides data for top-level composable functions , This function ( Top composable functions ) Use these data to describe the interface by calling other composable functions , Pass the appropriate data to these composable functions , And pass data down the hierarchy

Event response : Bottom up
 Insert picture description here

for example : Trigger onclick event , These events shall inform the application logic , The application logic can then change the state of the application . When the state changes , The system will call the composable function again with the new data . This causes the interface elements to be redrawn , This process is called “ restructuring ”.

Radio button click , The application logic changes the radio button status from check Turn into checked. A change in state leads to compose function restructuring

Caching temporary variables in composable functions is not recommended , Include anonymous functions , Unless it's very simple . It is suggested to extract the state and data outside the composable function to make the composable function idempotent

restructuring

1. Do not rely on the side effects of executing composable functions , Because you may skip the reorganization of functions

Collateral effect : Any changes visible to the rest of the application

 Write the properties of the shared object 
 to update  ViewModel  Observable items in 
 Update sharing preferences 

Composable functions may be re executed as frequently as each frame , If you need to perform expensive operations ( For example, reading data from shared preferences ), Please be there. [ Background coordination process ] In the implementation of , And pass the value result as a parameter to the composable function .

This document discusses you in Compose Matters needing attention when programming in :

Composable functions can be executed in any order :

Composable functions should be idempotent , You should not rely on the order in which you declare functions , Imagine that the program execution order is serialization

Composable functions can be executed in parallel .

If you look at the code for composable functions , You might think that these codes run in the order they appear . But it may not be so . If a composable function contains calls to other composable functions , These functions can be run in any order .Compose You can choose to recognize that some interface elements take precedence over other interface elements , So first draw these elements .

for example , Suppose you have the following code , Used to draw three screens in the tab layout :

@Composable
fun ButtonRow() {
    
    MyFancyNavigation {
    
        StartScreen()
        MiddleScreen()
        EndScreen()
    }
}

Yes StartScreen、MiddleScreen and EndScreen Can be called in any order . It means , for instance , You can't let StartScreen() Set a global variable ( Collateral effect ) And let MiddleScreen() Take advantage of this change . contrary , Each of these functions needs to remain independent .

Composable functions can run in parallel

Compose You can optimize reorganization by running composable functions in parallel . thus ,Compose You can use multiple cores , And run composable functions at a lower priority ( Not on the screen ).

This optimization means , Composable functions may execute in the background thread pool . If a composable function pair ViewModel Call a function , be Compose This function may be called from multiple threads at the same time .

In order to ensure the normal operation of the application , All composable functions should have no side effects , Instead, you should always execute on the interface thread onClick Wait for the callback to trigger side effects .

When a composable function is called , The call may occur on a different thread than the caller . It means , The use of modifiable combinations should be avoided lambda The code of the variable in , Because this kind of code is not thread safe code , And because it's composable lambda Disallowed side effects .

The following example shows a composable item , It displays a list and its number of items :

@Composable
fun ListComposable(myList: List<String>) {
    
    Row(horizontalArrangement = Arrangement.SpaceBetween) {
    
        Column {
    
            for (item in myList) {
    
                Text("Item: $item")
            }
        }
        Text("Count: ${
      myList.size}")
    }
}

This code has no side effects , It converts the input list into an interface . This code is perfect for displaying small lists . however , If the function writes a local variable , Then this is not thread safe or correct code :

@Composable
@Deprecated("Example with bug")
fun ListWithBug(myList: List<String>) {
    
    var items = 0

    Row(horizontalArrangement = Arrangement.SpaceBetween) {
    
        Column {
    
            for (item in myList) {
    
                Text("Item: $item")
                items++ // Avoid! Side-effect of the column recomposing.
            }
        }
        Text("Count: $items")
    }
}

In this case , Every reorganization , Will be modified items. This can be every frame of the animation , Or when the list is updated . But anyway , The interface will display the number of wrong items . therefore ,Compose Such a write operation is not supported ; By disabling such writes , We allow the framework to change threads to perform composable tasks lambda.

Reorganization skips as many composable functions and lambda.

Restructuring is an optimistic operation , May be cancelled :

as long as Compose Think that the parameters of a composable item may have changed , Will start restructuring . Restructuring is an optimistic operation , in other words ,Compose The reorganization is expected to be completed before the parameters change again . If a parameter changes before the reorganization is completed ,Compose May cancel the reorganization , And start again with the new parameters .

After canceling the reorganization ,Compose The interface tree will be discarded from the reorganization . If any side effects depend on the displayed interface , Then even if the composition operation is cancelled , This side effect will also be applied . This may lead to inconsistent application status .

Ensure that all composable functions and lambda Are idempotent and have no side effects , To deal with optimistic restructuring .

Composable functions can run as frequently as every frame of an animation
 The best practice is to keep composable functions fast 、 Idempotent with no side effects .

compose Programming idea https://developer.android.com/jetpack/compose/mental-model

原网站

版权声明
本文为[Lighthouse @kuaidao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211518337160.html