“记住"和“记住"有什么区别?和“可变状态"在 android jetpack 中编写? [英] What is the difference between "remember" and "mutableState" in android jetpack compose?

查看:37
本文介绍了“记住"和“记住"有什么区别?和“可变状态"在 android jetpack 中编写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 jetpack compose 的新手,试图理解 remembermutableStateOf

I'm new in jetpack compose and trying to understand the deference between remember and mutableStateOf


换句话说,这条线之间的尊重


In other words the deference between this line

val text = remember{ mutableStateOf("") }

还有这个

val text = remember{ "" }

还有这个

val text = mutableStateOf("")

推荐答案

remember 是一个可组合的函数,可用于缓存昂贵的操作.您可以将其视为可组合对象本地的缓存.

remember is a composable function that can be used to cache expensive operations. You can think of it as a cache which is local to your composable.

val state: Int = remember { 1 }

上面代码中的state是不可变的.如果您想更改该状态并更新 UI,您可以使用 MutableState.Compose 观察对 MutableState 对象的任何读取和写入,并触发 recomposition 以更新 UI.

The state in the above code is immutable. If you want to change that state and also update the UI, you can use a MutableState. Compose observes any reads and writes to the MutableState object and triggers a recomposition to update the UI.

val state: MutableState<Int> = remember { mutableStateOf(1) }

Text(
   modifier = Modifier.clickable { state.value += 1 },
   text = "${state.value}",
 )

另一种变体(在alpha12中添加)称为rememberSaveable,类似于remember,但存储的值可以在进程死亡或配置更改后幸存下来.

Another variant (added in alpha12) called rememberSaveable which is similar to remember, but the stored value can survive process death or configuration changes.

val state: MutableState<Int> = rememberSaveable { mutableStateOf(1) }

注意:您还可以使用属性委托作为语法糖来解开 MutableState.

Note: You can also use property delegates as a syntactic sugar to unwrap the MutableState.

var state: Int by remember { mutableStateOf(1) }

关于您问题的最后一部分,如果您在可组合中执行如下所示的操作,您只是在创建一个 MutableState 对象.

Regarding the last part of your question, if you are doing something like shown below within your composable, you are just creating a MutableState object.

val state: MutableState<Int> = mutableStateOf { 1 }

MutableState 是使用 LiveDataFlow 的替代方法.Compose 默认情况下不会观察到此对象的任何更改,因此不会发生重组.如果您希望观察更改并缓存状态,请使用 remember.如果不需要缓存而只想观察,可以使用derivedStateOf.这是一个 sample 如何使用它.

MutableState is an alternative to using LiveData or Flow. Compose does not observe any changes to this object by default and therefore no recomposition will happen. If you want the changes to be observed and the state to be cached use remember. If you don't need the caching but only want to observe, you can use derivedStateOf. Here is a sample of how to use it.

这篇关于“记住"和“记住"有什么区别?和“可变状态"在 android jetpack 中编写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆