https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

Czar

03/09/2020, 3:16 PM
I need to return last element of the flow along with its index, is there a prettier way?
s

streetsofboston

03/09/2020, 3:19 PM
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 }
}
2 Views