What is Kotlin Flow in android?

CodingWithTashi
2 min readMar 6, 2021
Kotlin flow defination
Photo by Matt Hardy on Unsplash

As per doc:

A suspending function asynchronously returns a single value, but how can we return multiple asynchronously computed values? This is where Kotlin Flows come in.

  • I think this has a perfect meaning of what is kotlin flow.
  • In normal coroutine, it return single value either Int,String,List or list etc in coroutine suspending function.
  • But what if you want stream of value say from 1 to 10,square of value from 1 to 10 etc from function, that is where Kotlin Flows come in.

I have read kotlin flow blogpost,documentation and watch few more tutorial as well. And I must tell you, If you have no idea about what is RxJava or Coroutine then this will be difficult to digest.

But let me give it a shot to put kotlin flow in your brain without refering much of post or any documentation.

Note: The sole purpose of this post is to make you understand what exactly kotlin flow and coroutine is and what arethe different between kotlin flow and coroutine suspenting function with an example.

Please check out official documention for more information.

So what is coroutine suspending function and kotlin flow?

Difference between coroutine and kotlin flow
kotlin coroutine vs flow

Coroutine example:

  • In this example, we are just return value 3 through coroutine function. We have used coroutine scope as Dispatchers.IO
  • You can used IO,Default,Main based on your requirement

Flow example:

  • We will emit numbers from 0 to 10 at 1delay. To emit the number we will use emit() which collects the value emitted.
  • It is part of FlowCollector which can be used as a receiver.and, at last, we use flowOn operator which means it shall be used to change the context of the flow emission.
  • Here, we can use different Dispatchers like IO, Default, etc.
    flowOn() is like subscribeOn() in RxJava
  • When we call startCollecting Function we will print the values one by one.
    flow.collect now will start extracting/collection the value from the flow on the Main thread as Dispatchers.
  • Main is used in launch coroutine builder in CoroutineScope

Checkout more blog from CodingWithTashi. Follow me on twitter or Instagram or YouTube.

That all,Thanks guys, I hope you like this shitty blog. please make sure to give clap 👏 and leave some engagement.

--

--