Search⌘ K
AI Features

Introduction to Flow

Explore how Kotlin Flow represents asynchronous streams of data with suspending functions. Understand the differences between Flow and Sequence for handling values computed over time. Learn why Flow is preferred for concurrency and non-blocking operations, and how to collect and process emitted elements safely in coroutine contexts.

A flow represents a stream of values that are computed asynchronously. The Flow interface allows the flowing elements to be collected, which means handling each element as it reaches the end of the flow (collect for Flow is like forEach for collections).

Kotlin 1.5
interface Flow<out T> {
suspend fun collect(collector: FlowCollector<T>)
}

As we can see, collect is the only member function in Flow. All others are defined as extensions. This is similar to Iterable or Sequence, which only have an iterator as a member function.

Kotlin 1.5
interface Iterable<out T> {
operator fun iterator(): Iterator<T>
}
interface Sequence<out T> {
operator fun iterator(): Iterator<T>
}

Comparing flow to other ways of representing values

The concept of flow should be well known to those using RxJava or Reactor, but others might need a better explanation. Imagine that we need a function to return more than a single ...