我读过文章,我知道流程需要在协同中操作,如代码A。
StateFlow从Flow继承下来,我认为我应该在一个协同系统中操作StateFlow。
代码B来自示例项目。
似乎fun openDrawer()在没有挂起函数的情况下直接操作MutableStateFlow,为什么?
码A
fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
fun main() = runBlocking<Unit> {
// Launch a concurrent coroutine to check if the main thread is blocked
launch {
for (k in 1..3) {
println("I'm not blocked $k")
delay(100)
}
}
// Collect the flow
simple().collect { value -> println(value) }
}码B
class MainViewModel : ViewModel() {
private val _drawerShouldBeOpened = MutableStateFlow(false)
val drawerShouldBeOpened: StateFlow<Boolean> = _drawerShouldBeOpened
fun openDrawer() {
_drawerShouldBeOpened.value = true
}
fun resetOpenDrawerAction() {
_drawerShouldBeOpened.value = false
}
}发布于 2021-10-29 09:20:50
这是因为写入value字段不需要suspend上下文。所以它的策划人不是suspend。
但是要实际订阅value更新,您需要suspend上下文,因为collect方法是suspend。
有关更多示例,请参见Android 文档。
https://stackoverflow.com/questions/69766354
复制相似问题