https://kotlinlang.org logo
#flow
Title
# flow
m

Mikael Alfredsson

11/24/2020, 6:23 AM
I want to make a generic class that combines and array of flows, runs a transformer and emits the result (the class should do more than this, so thats the reason to put it in a class rather than a function) this small example explains the problem
Copy code
class FlowGroup<T>(
    items:List<MutableSharedFlow<T>>,
    transform: suspend (Array<T>) -> T
) {
    val flow = MutableSharedFlow<T>()
    init {
        MainScope().launch {
            combine(items, transform).collect {
                flow.emit(it)
            }
        }
    }
}
combine
wont compile in this code because it uses the
reified
qualifier, and I don’t know how to get that into this function. Any suggestions?
m

Manuel Wrage

11/24/2020, 11:44 AM
You can do it likes this:
Copy code
class FlowGroup<T> private constructor(combinedFlow: Flow<T>) {
    val flow = MutableSharedFlow<T>()
    init {
        MainScope().launch { 
            combinedFlow.collect {
                flow.emit(it)
            }
        }
    }
    companion object {
        inline operator fun <reified T> invoke(
            items:List<MutableSharedFlow<T>>,
            noinline transform: suspend (Array<T>) -> T
        ) = FlowGroup<T>(combine(items, transform))
    }
}
m

Mikael Alfredsson

11/24/2020, 12:08 PM
Thanks.. It works, but if I want to make this an
open
class the code starts to get quite weird 🙂 Do you know why the combine function that takes a list of
flow
as input has to be
reified
(the ones with defined number of input flows are not)
m

Manuel Wrage

11/24/2020, 3:10 PM
The
combine
function calls
arrayOfNulls<T>
and the
T
of it is also marked as
reified
.
m

Mikael Alfredsson

11/24/2020, 3:11 PM
yes, I saw that, but I don’t know if there is any technical limitation that forces the function to set that
or is this just a decision by the kotlin team