简体   繁体   English

Jetpack Compose collectAsState 问题

[英]Jetpack Compose collectAsState issue

I'm using Composes collectAsState() function to collect from this StateFlow我正在使用 Composes collectAsState() function 从这个 StateFlow 收集

val _authToken = MutableStateFlow(AuthToken("", 0))
val authToken: StateFlow<AuthToken> = _authToken
val authToken by loginViewModel.authToken.collectAsState() // this returns AuthToken which is fine.

However, when turning a cold flow into a stateflow using the stateIn operator then using collectAsState() it returns a State version of the object which is odd then I need to call.value on collectAsState() to retrieve it.但是,当使用 stateIn 运算符将冷流转换为状态流然后使用 collectAsState() 时,它会返回 State 版本的 object,这很奇怪,然后我需要在 collectAsState() 上调用.value 来检索它。

Does anyone know why this happens?有谁知道为什么会这样?

val user = repository.getUser(viewModelScope).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
val user = profileViewModel.user.collectAsState() // returns State<User>

Replace代替

val user = profileViewModel.user.collectAsState() 

With

val user by profileViewModel.user.collectAsState() 

Well it IS supposed to return State.那么它应该返回状态。 Compose offers the delegate syntax to allow you to treat state as raw types. Compose 提供了委托语法,允许您将状态视为原始类型。

If you want to extract the data from State , you make use of the by keyword.如果要从State提取数据,请使用by关键字。 For example,例如,

var a : T by b : State<T> and, var a : State<T> = b : State<T> var a : T by b : State<T>var a : State<T> = b : State<T>

In your case, if you want user to be of type User and not State<User> , you should change the initialisation to在您的情况下,如果您希望user的类型为User而不是State<User> ,则应将初始化更改为

val user by profileViewModel.user.collectAsState() // returns User

Also, you should have known from the name of the method, it is collectAs State .此外,您应该从方法的名称中知道它是 collectAs State

With the new version for androidx.lifecycle:lifecycle-*:2.6.0-alpha01 , use collectAsStateWithLifecycle() instead对于androidx.lifecycle:lifecycle-*:2.6.0-alpha01的新版本,请改用collectAsStateWithLifecycle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM