When trying to collect from a Flow the type suddenly mismatches, and it was working and then started suddenly.

在我的viewmodel中:

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. 
    }
}

But collect gives the error: Type mismatch: inferred type is () -> Unit but FlowCollector<Int> was expected.

这怎么会发生?

推荐答案

可能你用的是the direct collect() function on Flow.

对于语法,需要使用import the collect() extension function.

(and I really wish that they did not name these the same...)

Kotlin相关问答推荐

如何防止Android Studio在每一行的选项卡凹痕和文本之间添加空白?

解决Microronaut中多个可能的Bean候选者冲突

同时也是一个字符串的 Kotlin 枚举

找不到有效的 Docker 环境

如何在 Kotlin 中将with代码转换为完整代码?

使用 Compose for Desktop Bundle 文件

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

kotlin 单例异常是好是坏?

OnClickListener 未在 ConstraintLayout 上触发

使用 Hilt 注入 CoroutineWorker

Kotlin:如何在活页夹中返回正在运行的服务实例?

Kotlin suspend fun

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

当被Spring代理类访问时,Kotlin实例变量为null

使用 Kotlin 创建自定义 Dagger 2 范围

在kotlin中初始化类变量的正确位置是什么

不推荐使用仅限生命周期的LifecycleEvent

Kotlin-将UTC转换为当地时间

如何在 spring-boot Web 客户端中发送请求正文?