Zoom Webinar: Learn and enhance your TypeScript skills | 28th March 2023 | 10 AM PST [10:30 PM IST] Register here

Introduction to the Kotlin Flow API



July 7, 2021


July 7, 2021

To build an Android application asynchronously, you might be using RxJava. In Kotlin, the same functionality is provided by Kotlin Flow API which is an addition to Kotlin Coroutine. The article introduces Kotlin Flow, why we need it, and how to create it.

In Android application development, UI is the most fundamental part that makes the first impression. As a result, it is critical to building it carefully to provide the best user experience. Asynchronous programming plays a major role in enhancing responsiveness and app performance.

For building applications asynchronously with Kotlin, Android developers use Coroutines. Kotlin Coroutines 1.2.0 alpha first released Flow API. With this, developers can handle streams of data that emit values sequentially.

Technically, when you add a Kotlin Coroutine library or dependency to your application, you also add Kotlin Flow as a part of Kotlin Coroutines.

What is Kotlin Flow?

Kotlin Flow

A flow is an asynchronous version of the sequence whose values are emitted lazily. Flow produces each value on-demand whenever it is required. Flow can emit multiple values sequentially opposite to the suspend function that returns only a single value.

Let us understand it using the following diagram,

Introduction to the Kotlin Flow API

When you request the data from a server using Retrofit and use asynchronous programming to handle incoming data, in such a scenario, Flow manages the incoming data asynchronously on the background thread, as there is a possibility of some processes running longer to fetch data. Once all the requested data is received, it is collected and displayed using recycler View.

Kotlin Flows are built on the top of coroutines, and the values emitted must be of the same type. For example, Flow will emit only integer values. Also, the flow will always emit data sequentially, and it uses a suspend function to produce and consume value asynchronously.

It means, with the Kotlin Flow API you can make a network request and produce the next value without blocking the main thread.

In the data stream, three entities are involved: a producer, intermediaries, and a consumer.

  • The producer produces the data added to the stream.
  • Intermediaries can modify each value emitted into the stream.
  • A consumer consumes value from the stream.

Entities involved in streams of data

Entities involved in streams of data

In an Android application, the Repository is a Producer of UI from where the data is displayed to the UI using a View which acts as a Consumer. On the other hand, View is the producer of user input events, and other layers in the hierarchy consume them.

The layer in between the producer and consumer acts as an intermediate responsible for modifying data streams to adjust to the requirement of the concerned layer.

Why Do We Need Flow?

Flow is built above the Coroutines that means you can transform or consume flows using Coroutines. With Flow, you can control concurrent coroutines by coordinating their executions.

Android developers that want to build an application asynchronously are familiar with Rx Java. It contains all the operators essential for reactive programming. The Kotlin Flow API provides similar functionality in Kotlin, it provides the functional operators such as map, flatMapLatest, Combine, and so on.

Besides that, it supports suspending functions on most operators. That helps you to perform the asynchronous task sequentially.

Creating a Flow

To create flows in Kotlin, you will need Flow Builder APIs. The flow builder function creates a new flow where you can manually emit values using the emit function as shown in the code snippet below.

// Creating a Flow
class NewsRemoteDataSource(
private val newsApi: NewsApi,
private val refreshIntervalMs: Long = 5000
) {
val latestNews: Flow<List> = flow {
while(true) {
val latestNews = newsApi.fetchLatestNews()
emit(latestNews) // Emits the result of the request to the flow
delay(refreshIntervalMs) // Suspends the coroutine for some time
// Interface that provides a way to make network requests with suspend fun
interface NewsApi {
suspend fun fetchLatestNews(): List }

The flow builder executes within a coroutine, and therefore it is benefited from the same asynchronous APIs, with some restrictions.

  • In the above example, the producer is suspended until the network request initiated by fetchLatestNews gets completed. After its completion, the result is emitted on the stream.
  • Also, with the flow builder, the Producer cannot emit values from a different Coroutine context. Therefore, you need to use other flow builders such as callbackFlow rather than creating a different coroutine.

There are some rules of Flow execution. By default, the flow will execute,

  • Every time a terminal operator is applied without the memory of the last run.
  • Until the terminal operator is canceled.
  • When the final value is fully processed, and the next value is requested.

A flow can participate in structured concurrency because of these rules, and it is safe to create a long-running coroutine from a Flow. Also, there is no risk of data leakage because flows are always cleaned up using coroutine cooperative cancellation rules once the caller is cancelled

The Kotlin Flow API is integrated into many Jetpack libraries, and it is popular among Android third-party libraries. It is the best fit for obtaining a continuous stream of live data and updates.

Kotlin is the most loved technology used by more than 60% of professional Android developers in the world. However, building an application takes a considerable amount of time and effort. But now it is possible to create your application 2x faster with DhiWise Kotlin Builder. Want to know how?

“Try Dhiwise Kotlin builder to finish your month’s work in weeks!!”

Happy Coding!!