当前位置:网站首页>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 
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 
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
边栏推荐
猜你喜欢

火山引擎+焱融 YRCloudFile,驱动数据存储新增长

Vscade tool

「运维有小邓」Active Directory批量修改用户

One trick: let logs help you make decisions through Yanrong SaaS data service platform +elk

硅橡胶玻纤管EN45545防火试验的难易程度

为什么RedisCluster设计成16384个槽?

Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which

【没搞懂路由策略?盘它!】

Integrated base scheme presentation

常见设置模式
随机推荐
Chapter V operation bit and bit string
The next stop of Intelligent Manufacturing: cloud native + edge computing two wheel drive
深入理解图注意力机制
Iframe cross domain value transfer
Bm19 looking for peak
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
Addition of 3DE grid coordinate points and objects
20 pyGame module to make a jumping ball game
module. Exports points to problems
程序员进修之路
Sorting out Android kotlin generic knowledge points
How to adjust 3DE 3D model view if you can't see it
【技术管理】集结号与亮剑团队
SCAU软件工程基础
Leetcode 25: a group of K flipped linked lists
PingCAP 入选 2022 Gartner 云数据库“客户之声”,获评“卓越表现者”最高分
3DE 三維模型視圖看不到怎麼調整
Android kotlin 类委托 by,by lazy关键
map和实体类互转的代码示例
AS 3744.1标准中提及ISO8191测试,两者测试一样吗?