Understanding Terminal Operators in Kotlin Flow

In this blog, we are going to learn about the Terminal Operators in Kotlin Flow. The Flow APIs in Kotlin Coroutines are very helpful when it comes to handling the stream of data.

Before starting, for your information, this blog post is a part of the series that we are writing on Flow APIs in Kotlin Coroutines.

Resources to get started with Kotlin Flow:

Let's get started.

What are Terminal Operators?

Terminal operators are the operators which actually start the flow by connecting the flow builder, operators with the collector.

For example:

(1..5).asFlow()
.filter {
    it % 2 == 0
}
.map {
    it * it
}.collect {
    Log.d(TAG, it.toString())
}

Here, collect is the Terminal Operator.

So, the most basic terminal operator is the collect operator which is the Collector.

So, if you just write the following, the flow will not start:

(1..5).asFlow()
.filter {
    it % 2 == 0
}
.map {
    it * it
}

You must use the terminal operator to start it, in this case, collect.

Let's see another Terminal Operator which is reduce Operator.

reduce: apply a function to each item emitted and emit the final value

val result = (1..5).asFlow()
    .reduce { a, b -> a + b }

Log.d(TAG, result.toString())

Here, the result will be 15.

Explanation:

At the initial stage, we have 1, 2, 3, 4, 5 which are going to be emitted.

Initially a = 0 and b = 1 which will keep on changing based on the steps.

Step 1:

a = 0, b = 1

a = a + b = 0 + 1 = 1

Step 2:

a = 1, b = 2

a = a + b = 1 + 2 = 3

Step 3:

a = 3, b = 3

a = a + b = 3 + 3 = 6

Step 4:

a = 6, b = 4

a = a + b = 6 + 4 = 10

Step 5:

a = 10, b = 5

a = a + b = 10 + 5 = 15

This is how the result will be 15.

This was all about the Terminal Operators.

That's it for now.

Also, Let’s become friends on Twitter, Linkedin, Github, Quora, and Facebook.