logo
logo
Sign in

Getting Started with Kotlin Flow

avatar
Expert App Devs
kotlin flow
If you are an Android developer and looking to develop an app asynchronously you might be using RxJava for that. RxJava has become one of the most important things to learn and use in Android.


A lot of people use Kotlin Coroutines. The New Kotlin Coroutine version released by Jetbrains came up with Flow API as part of it. With the help of Flow, you can handle a stream of data that emits values sequentially.

What are Flow APIs in Kotlin Coroutines?

Flow API is the best way to handle the stream of data asynchronously that executes in a sequential manner.

In RxJava, the Observables structure represents a stream of items. RxJava body does not execute until it is subscribed to by a subscriber. once it is subscribed, the subscriber starts getting the data items emitted. The same way follows in Flow works on the same condition where the code inside a flow builder does not run until the flow connection is done.

Start Integrating Flow APIs in your project

Add the following in the app's build.gradle,

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
and in the project's build.gradle add,

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61"

for the settle flow setupFlow() I will emit items after a 500milliseconds delay.

fun setupFlow(){
    flow = flow {
        Log.d(TAG, "Start flow")
        (0..10).forEach {
            delay(500)
            Log.d(TAG, "Emitting $it")
            emit(it)

        }
    }.flowOn(Dispatchers.Default)
}

Now we are going to write a code for printing the values which we received from the flow.

private fun setupClicks() {
    button.setOnClickListener {
        CoroutineScope(Dispatchers.Main).launch {
            flow.collect {
                Log.d(TAG, it.toString())
            }
        }
    }
}

Migrating from LiveData to Kotlin’s Flow

continue reading: Getting Started with Kotlin Flow

 

collect
0
avatar
Expert App Devs
guide
Zupyak is the world’s largest content marketing community, with over 400 000 members and 3 million articles. Explore and get your content discovered.
Read more