Affection77
Affection77

Reputation: 69

flow.collect(suspend (T) -> Unit) doesn't work with the newer version of coroutines dependencies

I updated the gradle file

from

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

to

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0'

What happened was that the following function started to throw error.

fun <T> Fragment.collectLifeCycleFlow(flow: Flow<T>, collector: suspend (T) -> Unit) {
    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
            flow.collect(collector)
        }
    }
}

However, it works fine with flow.collectLatest(collector)

I don't know why collect() doesn't accept parameters anymore. Please help with me.

Upvotes: 1

Views: 2788

Answers (1)

Tenfour04
Tenfour04

Reputation: 93834

Flow.collect now takes a FlowCollector functional interface argument instead of a suspend (T) -> Unit.

This function was always there, but it was marked with an annotation that prevented you from using it and there was a separate collect extension function that adapted suspend (T) -> Unit into a FlowCollector<T>. Now the base collect function is publicly usable and they removed that extension function. The plus side is you no longer have to deal with having to manually import the extension function. The previous behavior caused collect to not compile, but the IDE didn't suggest how to import the extension function in an easy manner.

By the way, you should be using viewLifecycleOwner in a Fragment!

Here is your fixed code:

fun <T> Fragment.collectLifeCycleFlow(flow: Flow<T>, collector: FlowCollector<T>) {
    viewLifecycleOwner.lifecycleScope.launch {
        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            flow.collect(collector)
        }
    }
}

Upvotes: 2

Related Questions