I need to return last element of the flow along wi...
# coroutines
c
I need to return last element of the flow along with its index, is there a prettier way?
s
Using reduce seems a bit of overkill. What about
flow.withIndex().toList().last()
?
If you’d like to make a more performant one, you could could create your own extension function, something like:
Copy code
suspend fun <T> Flow<T>.lastWithIndex(): Pair<Int, T>? {
  var index = -1
  var result: T? 
  collect { result = it; index++ }
  return result?.let { index to it }
}