Jetpack Compose collectAsState 问题

时间:2021-07-23 12:55:18

标签: android android-jetpack-compose

我正在使用 Composes collectAsState() 函数从这个 StateFlow 中收集

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

但是,当使用 stateIn 运算符将冷流转换为状态流然后使用 collectAsState() 时,它返回对象的 State 版本,这很奇怪,然后我需要在 collectAsState() 上调用 .value 来检索它。

有人知道为什么会这样吗?

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

2 个答案:

答案 0 :(得分:1)

替换

val user = profileViewModel.user.collectAsState() 

val user by profileViewModel.user.collectAsState() 

答案 1 :(得分:1)

好吧,它应该返回 State。 Compose 提供了委托语法,允许您将状态视为原始类型。

如果您想从 State 中提取数据,请使用 by 关键字。例如,

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

在您的情况下,如果您希望 user 的类型为 User 而不是 State<User>,您应该将初始化更改为

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

另外,您应该从方法的名称中知道它是 collectAsState