Terminal Operators in Kotlin Flow

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
Terminal Operators in Kotlin Flow

I am Amit Shekhar, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join my program and get high paying tech job: amitshekhar.me

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

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.

This blog is a part of the series I have written on Flow API in Kotlin:

Let's get started.

What are Terminal Operators?

Terminal operators are the operators that 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.

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.