Determining when a Flow returns no data

Viewed 1004

The Kotlin flow states the following:

A suspending function asynchronously returns a single value, but how can we return multiple asynchronously computed values? This is where Kotlin Flows come in.

However, if the source of my flow is such that when it completes but returns no data, is there a way to determine that from the flow? For example, if the source of the flow calls a backend API but the API returns no data, is there a way to determine when the flow completes and has no data?

3 Answers

If the API returns a Flow, it is usually expected to return 0 or more elements. That flow will typically be collected by some piece of code in order to process the values. The collect() call is a suspending function, and will return when the flow completes:

val flow = yourApiCallReturningFlow()

flow.collect { element ->
   // process element here
}

// if we're here, the flow has completed

Any other terminal operator like first(), toList(), etc. will handle the flow's completion in some way (and may even cancel the flow early).

I'm not sure about what you're looking for here, but for example there is a terminal operator count:

val flow = yourApiCallReturningFlow()

val hasAnyElement = flow.count() == 0

There is an onEmpty method that will invoke an action if the flow completes without emitting any items.

It can also be used to emit a special value to the flow to indicate that it was empty. For example, if you have a flow of events you can emit an EmptyDataEvent.

Or you can just do whatever it is that you want to do inside this onEmpty lambda.

Highly related is also the onCompletion method

You can just do toList() on the flow and check if it's empty

Related