How do I get the ---last--- element of a `Flow` wi...
# coroutines
d
How do I get the ---last--- element of a
Flow
without having to use
toList().last()
...?
j
something like
Copy code
suspend fun <T> Flow<T>.last(): T? {
  var last: T? = null
  collect {
    last = it
  }
  return last
}
👍🏼 2
d
Thanks!
j
you could also do
Copy code
suspend fun <T> Flow<T>.last(): T {
  val marker = Any()
  var last: Any? = marker
  collect {
    last = it
  }
  if (last === marker) throw NoSuchElementException()
  return last as T
}
👍 4
depends on the behavior you want
d
Nice 🙂! I also didn't know that
Any()
could be instantiated and used like that... also good to know!