Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 824
just_user Avatar asked Jun 12 '20 15:06

just_user


2 Answers

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

like image 66
CommonsWare Avatar answered Oct 15 '22 20:10

CommonsWare


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.

like image 39
Kenneth Murerwa Avatar answered Oct 15 '22 19:10

Kenneth Murerwa