Flow Intermediate Operator

Vignesh PrabhuVignesh Prabhu
2 min read

In this series of articles , we are discussing about Kotlin flows and in this article we will discuss about Flows Intermediate Operators

Code : https://gist.github.com/vprabhu/04cd8f6eaeecaf0d3de72049d023eddf

Sample Android App :

Code : https://github.com/vprabhu/FlowUpdateUI/

This simple android app demos how to update compose UI ( Progress bar and result text) with the help of flow operators .

What is Intermediate Operators?

  • These operators can transform the flow

  • These operators are applied to upstream flow and return a downstream flow

  • These operators are not suspending function means it executes instantly and return a new transformed flow.

In this article ,we will learn about most used operators in Android app development.

onStart()

Syntax:

fun <T> Flow<T>.onStart(action: suspend FlowCollector<T>.() -> Unit): Flow<T>(source)

As we can see from above syntax ,

The action block is executed before the collection of flow and this is called before the upstream starts

onEach()

Syntax:

fun <T> Flow<T>.onEach(action: suspend (T) -> Unit): Flow<T>(source)

  • As the name implies , this operator is executed on emission of each value

  • returns a flow after executing the action on each value/item from the upstream flow to downstream flow

onCompleted()

Syntax:

fun <T> Flow<T>.onCompletion(action: suspend FlowCollector<T>.(cause: Throwable?) -> Unit): Flow<T>(source)

  • As the name implies , this operator is executed after the flow is completed or cancelled.

  • cause:Throwable -> this return null when the flow is completed and the same will return exception if the flow is cancelled .

In the next article , we will discuss about Flow Cancellation.

Please leave your comments to improve and discuss more

Happy and Enjoy coding

1
Subscribe to my newsletter

Read articles from Vignesh Prabhu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vignesh Prabhu
Vignesh Prabhu

I am an Android application developer who is looking for new challenges to solve , love to learn and implement new things in coding