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

Viewed 4508

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?

3 Answers

I encountered the same problem while trying to collect multiple flows from some datastore files. First of all, make sure that you have imported these two dependencies in your app-level gradle file. Also ensure that you replace the version numbers with suitable versions.

implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-beta01")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")

After syncing your gradle files, import collect;

import kotlinx.coroutines.flow.collect

Your collect{ } should now work correctly.

For me the solution was to put parenthesis at the end of collect:

viewModel.river.collect()

Related