1
votes

Is there a way to sort a collection emitted by a flow in a custom order like:

fun getList():Flow<Something>

fun main(){
   launch{
       getList().filter{}.map{}.sortBy{
                //
       }.toList()
   }
}
2

2 Answers

5
votes

You can toList() first and then sortBy(). Sorting a flow does not always make sense because a flow, by definition, does not know if there are going to be any more elements in the stream.

1
votes

You can apply some actions like that:

getList().transform {
    //it - list
    // sortedList - some function to perform sorting or something else
    emit(sortedList(it))
}

UPD: You can use map(similar to "transform", but more simple) and filter(it's used to emit only specific values of the flow) functions as well to perform some actions. "transform" function allows you to perform more specific actions. In that case they are same.

getList().map {
    sortedList(it)
}