alf*_*tap 2 android android-jetpack-compose
我正在使用 Compose CollectAsState() 函数从此 StateFlow 收集
val _authToken = MutableStateFlow(AuthToken("", 0))
val authToken: StateFlow<AuthToken> = _authToken
val authToken by loginViewModel.authToken.collectAsState() // this returns AuthToken which is fine.
Run Code Online (Sandbox Code Playgroud)
但是,当使用 stateIn 运算符将冷流转换为状态流然后使用collectAsState() 时,它会返回对象的状态版本,这很奇怪,然后我需要在collectAsState() 上调用.value 来检索它。
有谁知道为什么会发生这种情况?
val user = repository.getUser(viewModelScope).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
val user = profileViewModel.user.collectAsState() // returns State<User>
Run Code Online (Sandbox Code Playgroud)
代替
val user = profileViewModel.user.collectAsState()
Run Code Online (Sandbox Code Playgroud)
和
val user by profileViewModel.user.collectAsState()
Run Code Online (Sandbox Code Playgroud)
好吧,它应该返回状态。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
另外,您应该从该方法的名称中知道,它是collectAs State。
| 归档时间: |
|
| 查看次数: |
6219 次 |
| 最近记录: |