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

Vivek Sharma

02/08/2021, 1:32 PM
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

wasyl

02/08/2021, 1:35 PM
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

Vivek Sharma

02/08/2021, 1:46 PM
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

wasyl

02/08/2021, 1:48 PM
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

gildor

02/08/2021, 1:51 PM
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

Vivek Sharma

02/08/2021, 2:09 PM
okay I got it thanks @Luka @gildor
2 Views