Jetpack Compose Side Effects in Details 副作用的详细信息

What is Side Effect’s? 副作用是什么?

Side Effects is a change in the state of the application that occurs outside the scope of the composable function and is not related to the UI. In non-UI related state changes, our screen may recompose more than necessary. This causes performance loss in our application.
副作用是指在可组合函数范围之外发生的应用程序状态更改,并且与 UI 无关。在非 UI 相关的状态更改中,我们的屏幕可能会进行不必要的重组。这会导致我们的应用程序性能下降。

  • API request as a result of the user clicking the button.
    用户单击按钮后产生的 API 请求。
  • Database operations in the application.
    应用程序中的数据库操作。

LaunchedEffect

LaunchedEffect, takes two arguments, key for representing when should it be executed and block to declare the lambda function. Whenever the key value changes, this lambda is triggered and the functions in scope are executed. If the key is not defined, then it gets executed only when the initial composition occurs and updates the UI.
LaunchedEffect 接受两个参数,key 用于表示何时执行,以及 block 来声明 lambda 函数。每当键值发生变化时,就会触发此 lambda 并执行作用域中的函数。如果未定义该键,则仅在初始组合发生并更新 UI 时执行它。

The most important feature of Launched Effect is that it can work with asynchronous processes and initialise Coroutines.
Launched Effect 最重要的特点是它可以与异步进程一起工作并初始化协程。

@Composable
fun Header() {var launchEffectState by remember { mutableStateOf(true) }var defaultState by remember { mutableStateOf(true) }val context = LocalContext.currentLaunchedEffect(key1 = launchEffectState) {Toast.makeText(context, "Launch Effect State Tetiklendi!", Toast.LENGTH_LONG).show()}Toast.makeText(LocalContext.current, "Default State Tetiklendi!", Toast.LENGTH_LONG).show()Column(modifier = Modifier.fillMaxSize(),horizontalAlignment=Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {Text(modifier = Modifier.clickable { launchEffectState = !launchEffectState },text = "Launch Effect State: $launchEffectState",fontSize = 32.sp)Spacer(modifier = Modifier.height(16.dp))Text(modifier = Modifier.clickable { defaultState = !defaultState },text = "Default state: $defaultState",fontSize = 32.sp)}
}

DisposableEffect

The Disposable Effect is triggered when the composable function is first created, then used to release the resource it uses when the composable is removed from the screen.
Disposable Effect 在首次创建可组合函数时触发,然后用于在可组合函数从屏幕上移除时释放其使用的资源。

Disposable Effect Block: This block defines the operations in DisposableEffect. This is typically when the Composable is initially displayed or when its parent Composable is initially composed. It is usually used to initialise a resource or start another interaction.
**Disposable Effect 块:**该块定义了 DisposableEffect 中的操作。这通常是在可组合项最初显示时或其父可组合项最初组合时。它通常用于初始化资源或启动另一个交互。

OnDispose Block: The code inside the onDispose block is executed when the Composable is removed from the composition. In this block, operations such as cleaning or deactivating resources are executed.
**OnDispose 块:**当从组合中删除可组合项时,将执行 onDispose 块内的代码。在该块中,执行清理或停用资源等操作。

@Composable
fun TimerScreen() {val elapsedDuration = remember { mutableStateOf(0) }DisposableEffect(Unit) {val scope = CoroutineScope(Dispatchers.Default)val job = scope.launch {while (true) {delay(1000)elapsedDuration.value += 1println("The timer is still running ${elapsedDuration.value}")}}onDispose {//job.cancel()println("Timer cancelled ${elapsedDuration.value}")}}Text(text = "Geçen Süre: ${elapsedDuration.value}",modifier = Modifier.padding(16.dp),fontSize = 24.sp)
}@Composable
fun RunTimerScreen() {val isVisible = remember { mutableStateOf(true) }Column(horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {Spacer(modifier = Modifier.height(10.dp))if (isVisible.value)TimerScreen()Button(onClick = { isVisible.value = false }) {Text("Hide Timer")}}
}

rememberCoroutineScope

Composable is used to start the coroutine as a result of a trigger in the function. For example, it is used in cases such as making a network request as a result of the user clicking a button. This is particularly useful when you need to launch and manage coroutines within Jetpack Compose components, ensuring that they are canceled appropriately when the Composable is removed from the UI hierarchy.
可组合用于在函数中触发时启动协程。例如,它用于诸如由于用户单击按钮而发出网络请求的情况。当您需要在 Jetpack Compose 组件中启动和管理协程时,这特别有用,确保在从 UI 层次结构中删除 Composable 时适当地取消它们。

@Composable
fun Header(scope: CoroutineScope) {var state by remember { mutableStateOf(true) }val context = LocalContext.currentColumn(modifier = Modifier.fillMaxSize(),horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {Text(modifier = Modifier.clickable {scope.launch {delay(3000)Toast.makeText(context, "Hello world $state", Toast.LENGTH_LONG).show()}},text = "Hello world $state",fontSize = 32.sp)Spacer(modifier = Modifier.height(16.dp))Text(modifier = Modifier.clickable {state = !state},text = "Hello amigo $state",fontSize = 32.sp)}
}

rememberCoroutineScope vs LaunchedEffect

LaunchedEffect should be used when you want that some action must be taken when your composable is first launched/relaunched (or when the key parameter has changed).
当您希望在首次启动/重新启动可组合项时(或当关键参数发生更改时)必须执行某些操作时,应使用LaunchedEffect
rememberCoroutineScope on the other hand, is specific to store the Coroutine scope allowing the code to launch some suspend function.
另一方面, rememberCoroutineScope 专门用于存储 Coroutine scope,允许代码启动某些挂起函数。

The example above shows the code blocks that display a list of type Booking. When remembercoroutinescope is used in the example on the left, a new network request will be made every time the screen is recomposed. In the Launched Effect example on the right, the recomposition is not affected by the recomposition status and the request will be made only when the screen is loaded for the first time.
上面的示例展示了显示 Booking 类型列表的代码块。当左侧示例中使用remembercoroutinescope时,每次界面重组时都会发出新的网络请求。在右侧的 Launched Effect 示例中,重组不受重组状态的影响,仅在第一次加载屏幕时才会发出请求。

SideEffect

Just like in Luanch Effect, we write the codes that we do not want to run in every recompose under the Side Effect scope. The most important difference from Launch Effect is that Side Effect does not work with coroutine.
就像在 Luanch Effect 中一样,我们在 Side Effect 范围内编写了不想在每次重构中运行的代码。与 Launch Effect 最重要的区别是 Side Effect 不能与协程一起使用。

@Composable
fun WithOutSideEffectExample() {val count = remember { mutableStateOf(0) }SideEffect {println("Count is ${count.value}")}Button(onClick = { count.value++ }) {Text(text = "Click here!")}
}

derivedStateOf

derivedStateOf should be used when your state or key changes more than you want to update your UI. We solve this problem by filtering between derivedStateOf scopes. It can be extremely effective in minimising recomposition.
当您的状态或键更改超过您想要更新 UI 的程度时,应使用 derivedStateOf。我们通过在衍生状态范围之间进行过滤来解决这个问题。它可以非常有效地减少重组。

rememberUpdatedState

The rememberUpdatedState is a side effect handler provided by Jetpack Compose that is used to ensure that a Composable always reflects the most up-to-date state when it’s recomposed. It’s particularly useful when you need to work with a snapshot of some state that might change during the composition process.
rememberUpdatedState 是 Jetpack Compose 提供的副作用处理程序,用于确保 Composable 在重构时始终反映最新状态。当您需要处理在合成过程中可能发生变化的某些状态的快照时,它特别有用。

@Composable
fun Header() {var caller by remember { mutableStateOf("Default") }Column(horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {Text(modifier = Modifier.clickable { caller = "First Text" },text = "Clicked, $caller",color= Color.Black,fontSize = 32.sp)Text(modifier = Modifier.clickable { caller = "Second Text" },text = "Clicked, $caller",color= Color.Blue,fontSize = 32.sp)CallTimer(caller)}
}
@Composable
fun CallTimer(caller: String) {println("Composable: $caller")val updated by rememberUpdatedState(newValue =caller )LaunchedEffect(key1 = Unit) {delay(7000)println("LaunchedEffect: $caller")}
}

produceState

produceState is a simple concept that combines the functionality of remember and LaunchedEffect. It creates a state variable and then updates the value of the state variable based on the results of a side effect. This can be used to ensure that your composables are always displaying the latest data.
ProduceState 是一个简单的概念,结合了 Remember 和 LaunchedEffect 的功能。它创建一个状态变量,然后根据副作用的结果更新状态变量的值。这可用于确保您的可组合项始终显示最新数据。

The produce state composable takes initialValue and producer. InitialValue is the initial value of the state variable. Producer is a lambda that defines the side effect that will be executed to update the value of the state variable. This lambda will be executed when the produce state composable is first composed, and it will be executed again whenever the value of the state variable changes.
生产状态可组合项采用初始值生产者。 InitialValue 是状态变量的初始值。 Producer 是一个 lambda,它定义将执行以更新状态变量值的副作用。该 lambda 将在第一次组合生成状态可组合项时执行,并且每当状态变量的值发生变化时都会再次执行。

@Composable
fun MyComposition() {var isLoading: Boolean by remember { mutableStateOf(true)}val data: String by produceState(initialValue = "") {value = getData()isLoading = false}Column(horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {if (isLoading) {CircularProgressIndicator()} else {Text(text = data)}}
}suspend fun getData(): String {delay(4000) // simulate a long-running operationreturn "Data loaded from a data source"
}

Jetpack Compose Side Effects in Details | by Nasuh Ünal | Sep, 2024 | Medium

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/423897.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

828华为云征文 | 使用华为云X实例部署图数据库Virtuoso并存储6500万条大数据的完整过程与性能测评

前言 在大数据时代,图数据库以其强大的关系处理能力在复杂网络、社交媒体分析、知识图谱等领域得到了广泛应用。而在云计算的蓬勃发展下,使用云服务器进行图数据库的部署与管理变得更加方便高效。本篇文章将详细介绍如何在华为云X实例上部署开源图数据…

中秋假期也能及时回应客户:微信聚合管理系统,自动回复

中秋佳节是阖家团圆的日子,很多人选择在此期间休息放松。但作为一名职场人士,如何在假期中不遗漏客户咨询? 不妨试试这个WeBot助手,你可以进行微信自动回复设置,轻松实现假期与工作两不误。 同一界面聚合多个账号 通…

HOT 100(七)栈、堆、贪心算法

一、栈 1、每日温度 使用单调递减栈来解决。主要思路是遍历temperatures数组,利用栈来存储还没有找到比当前温度高的天数的索引。当遇到比栈顶索引所对应温度更高的温度时,就可以确定当前这一天的温度比之前那一天高。索引的差值就是等待的天数。 求一…

使用c#制作一个小型桌面程序

封装dll 首先使用visual stdio 创建Dll新项目,然后属性管理器导入自己的工程属性表(如果没有可以参考visual stdio 如何配置opencv等其他环境) 创建完成后 系统会自动生成一些文件,其中 pch.cpp 先不要修改,pch.h中先导入自己需…

Unet改进31:添加Star_Block(2024最新改进方法)|紧凑的网络结构和高效的运算

本文内容:在不同位置添加Star_Block 目录 论文简介 1.步骤一 2.步骤二 3.步骤三 4.步骤四 论文简介 最近的研究引起了人们对网络设计中尚未开发的“星型操作”(元素智能乘法)潜力的关注。虽然有很多直观的解释,但其应用背后的基本原理在很大程度上仍未被探索。我们的研…

旅游网站设计与实现:SpringBoot技术手册

第三章 系统分析 开发一个系统首先要对系统进行分析,是开发者针对系统实际客户对软件应用的一个调查访问和研究,弄清用户对软件需求的具体要求,同时开发者还要对系统开发的经济和可技术上是否可行进行分析,并确定系统开发的成本和…

OZON电子产品大幅增长,OZON跨境PS5销量激增

Top1 存储卡 Карта памяти Canvas Select Plus 128 ГБ 商品id:1548303593 月销量:2131 欢迎各位卖家朋友点击这里: 👉 D。DDqbt。COm/74rD 免费体验 随着智能手机和平板电脑的普及,用户对于存储空…

C++笔记---继承(上)

1. 继承的简单介绍 1.1 继承的概念 继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允许我们在保持原有类特性的基础上进行扩展,增加方法(成员函数)和属性(成员变量),这样产生新的类,称派生类。 继承呈…

使用LDAP登录GitLab

使用LDAP登录GitLab gitlab.rb 配置如下 gitlab_rails[ldap_enabled] true #gitlab_rails[prevent_ldap_sign_in] false###! **remember to close this block with EOS below** gitlab_rails[ldap_servers] YAML.load <<-EOSmain:label: LDAPhost: 172.16.10.180port:…

python环境安装

一、下载开发IDE https://www.jetbrains.com/pycharm/download/?sectionwindows 下载:conda Download Now | Anaconda 重新打开PyCharm Community Edition 2024.2.1 新建项目&#xff1a;pythonProject1 编写python 文件时没有提示&#xff1a;错误:未选择 Python 解释器。请…

云轴科技ZStack 获鲲鹏应用创新大赛2024上海赛区决赛一等奖

9月13日&#xff0c;鲲鹏应用创新大赛2024上海赛区决赛成功举办。经评委专家从方案创新性、技术领先性、商业前景以及社会价值四个维度严格评审&#xff0c;云轴科技ZStack参赛作品《ZStack鲲鹏原生开发方案》荣获上海赛区企业赛——原生开发赛道&#xff08;互联网&#xff09…

线程 - 线程的由来、进程和线程的关系、进程创建_等待_退出详解

文章目录 一、线程概念1. 线程的出现2. linux 对线程的设计3. 线程二、进程和线程1. 进程和线程的关系2. 进程的调度3. 轻量级进程三、pthread库1. pthread 库的作用2. 手动链接 pthread库四、创建线程1. pthread_create()2. 函数的使用3. 线程和函数五、线程等待1. 新线程的运…

ROADM(可重构光分插复用器)-介绍

1. 引用 https://zhuanlan.zhihu.com/p/163369296 https://zhuanlan.zhihu.com/p/521352954 https://zhuanlan.zhihu.com/p/91103069 https://zhuanlan.zhihu.com/p/50610236 术语&#xff1a; 英文缩写描述灰光模块彩光模块CWDM&#xff1a;Coarse Wave-Length Division …

WireShark分析localhost包

文章目录 需要npcap。 java 需要配置Npcap&#xff0c;如果没有需要卸载重新安装 Npcap 是专为 Windows 开发的一款网络抓包 SDK&#xff0c;该 SDK 提供了被应用程序调用的库文件和系统驱动程序。通过 Npcap&#xff0c;我们可以得到原始&#xff08;raw&#xff09;网络数据&…

Java手写RPC框架-01-开篇

项目背景 随着业务不断升级&#xff0c;系统规模不断扩大&#xff0c; 单体架构会产生越来越多的问题&#xff0c;需要引入微服务将原先架构解耦为一个个模块。每个服务模块放在不同的服务器上&#xff0c;能够保证系统在高并发环境下的正常运转。 各个服务模块之间如何相互调…

OpenHarmony(鸿蒙南向开发)——轻量系统STM32F407芯片移植案例

往期知识点记录&#xff1a; 鸿蒙&#xff08;HarmonyOS&#xff09;应用层开发&#xff08;北向&#xff09;知识点汇总 鸿蒙&#xff08;OpenHarmony&#xff09;南向开发保姆级知识点汇总~ OpenHarmony&#xff08;鸿蒙南向开发&#xff09;——轻量和小型系统三方库移植指南…

【getshell】phpmyadmin后台getshell(4.8.5)

&#x1f3d8;️个人主页&#xff1a; 点燃银河尽头的篝火(●’◡’●) 如果文章有帮到你的话记得点赞&#x1f44d;收藏&#x1f497;支持一下哦 【getshell】phpmyadmin后台getshell&#xff08;4.8.5&#xff09; 一、进入sql命令输入界面二、上传代码三、getshell 一、进入…

Kubernetes (k8s)v1.27.1版本安装步骤

这 一、k8s 安装步骤1.1 安装docker及containerd容器1.2、设置每台服务器的参数1.3、安装kubelet、kubeadm、kubectl1.4、修改 kubelet 的 cgroup 和 docker 的 cgroup-driver 保持一致1.5、使用containerd 默认容器的配置1.6、使用kubeadm进行初始化1.7、初始化成功1.8、集群部…

海外云手机有哪些推荐?

随着云手机的发展&#xff0c;越来越多的企业和个人开始使用云手机来满足他们的海外业务需求。用户可以通过云手机实现方便、快捷的海外访问&#xff0c;一般用来进行tiktok运营、亚马逊电商运营、海外社媒运营等操作。海外云手机平台有很多&#xff0c;以下是一些比较好的云手…

✨机器学习笔记(四)—— 逻辑回归、决策边界、过拟合、正则化

Course1-Week3: https://github.com/kaieye/2022-Machine-Learning-Specialization/tree/main/Supervised%20Machine%20Learning%20Regression%20and%20Classification/week3机器学习笔记&#xff08;四&#xff09; 1️⃣逻辑回归&#xff08;logistic regression&#xff09;…