Home > Software design >  Determining when a Flow returns no data
Determining when a Flow returns no data

Time:10-14

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related