Type mismatch inferred type is () -> Unit but FlowCollector was expected

Issue

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

In my viewmodel:

class MyViewModel: ViewModel() {

    lateinit var river: Flow<Int>

    fun doStuff() {
        river  flow {
            emit(1)
        }.flowOn(Dispatchers.Default)
        .catch {
            emit(0)
        }
    }
}

Then in my activity I have the following:

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.

How could this be happening?

Solution

Probably, you are using the direct collect() function on Flow.

For your syntax, you need to import the collect() extension function.

(and I really wish that they did not name these the sameā€¦)

Answered By – CommonsWare

Leave a Comment