while using flow.first() operator, it throws excep...
# coroutines
v
while using flow.first() operator, it throws exception when flow is empty as docs say, but I am fetching list from database using a flow and checking if that flow.first() , and if the list is empty , does it mean flow is empty ?
w
What are you asking specifically?
first()
does exactly what it says, returns the first element, or throws if the flow completes before emitting anything
If you have a
Flow<List<T>>
then
first()
will still do the same thing, if nothing is emitted and the flow completes then
first()
will throw an exception. If the flow emits a value, it will return that value
If that value is an empty list, you’ll get an empty list
v
I am asking that if I get empty list emitted from flow, will
first()
throw exception ?
when flow will be empty or say will not emit anything?
w
It will not throw an exception because the flow is not empty, an empty list is a value
It’s easy to check yourself
Copy code
val result = flowOf(emptyList<String>())
    .first()
println(result)
g
Usually Flow from database never complete, it just emit current state of your request, so first() will suspend until it receive first result and after that return it
v
okay I got it thanks @Luka @gildor