尝试从Flow收集时,类型突然不匹配,并且正在运行,然后突然开始。
在我的视图模型中:
class MyViewModel: ViewModel() {
lateinit var river: Flow<Int>
fun doStuff() {
river = flow {
emit(1)
}.flowOn(Dispatchers.Default)
.catch {
emit(0)
}
}
}
然后在我的活动中,我有以下内容:
lifecycleScope.launch {
viewModel.river.collect { it ->
// this whole collect is what has the error.
}
}
但是collect
给出了错误:Type mismatch: inferred type is () -> Unit but FlowCollector<Int> was expected
。
这怎么可能发生?
答案 0 :(得分:15)
可能您正在使用the direct collect()
function on Flow
。
对于您的语法,您需要import
the collect()
extension function。
(我真的希望他们不要使用相同的名字...)
答案 1 :(得分:0)
对我来说,解决方案是将括号放在collect
的末尾:
viewModel.river.collect()