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?
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...)
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. Make sure to replace 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With