Kotlin Flow API

Abhishek Srivastava
12 min readAug 16, 2020

If you are an Android developer and looking to build an app asynchronously you might be using RxJava as it has an operator for almost everything. RxJava has become one of the most important things to know in Android.

But with Kotlin a lot of people tend to use Co-routines. With Kotlin Coroutine 1.2.0 alpha release Jetbrains came up with Flow API as part of it. With Flow in Kotlin now you can handle a stream of data that emits values sequentially.

A flow is an asynchronous version of a Sequence, a type of collection whose values are lazily produced. Just like a sequence, a flow produces each value on-demand whenever the value is needed, and flows can contain an infinite number of values.

In Kotlin, Coroutine is just the scheduler part of RxJava but now with Flow APIs coming along side it, it can be alternative to RxJava in Android.

In this blog, we will see how Flow APIs work in Kotlin and how can we start using it in our android projects. We will cover the following topics,

  • Types of flow
  • Why Needs Flow
  • What is Flow APIs in Kotlin Coroutines?
  • How does flow run
  • When does flow run
  • Start Integrating Flow APIs in your project
  • Builders in Flows
  • Few examples using Flow Operators.

Now let’s discuss one by one:-

Types of Flow?

Flows are based on suspending functions and they are completely sequential, while a coroutine is an instance of computation that, like a thread, can run concurrently with the other code.

Sequential flows

To get a better feel of the sequential nature of flows, take a look at the same example flow that emits ten integers with 100 ms delay between them:

Let us confirm that collecting it takes around a second:

val time = measureTimeMillis {
ints.collect { println(it) }
}
println(“Collected in $time ms”)

After execute out will be as below

1 
2
3
4
5
6
7
8
9
10
Collected in 1041 ms
Abhishek Srivastava

Senior Software Engineer | Android | Java | Kotlin | Xamarin Native Android | Flutter | Go