Creating Flow Using Flow Builder in Kotlin

In this blog, we are going to discuss the different types of flow builders and how to create Flow using Flow Builder. We will learn to create Flow with examples.
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:
- What is Flow in Kotlin?
- Understanding Terminal Operators in Kotlin Flow
- Exception Handling in Kotlin Flow
- Kotlin Flow Zip Operator
- Instant Search Using Kotlin Flow Operators
- Learn Kotlin Flow in Android by Examples
- Kotlin Flow Retry Operator with Exponential Backoff Delay
Let's get started.
We are going to cover the following:
- Types of flow builders
- Creating Flow Using Flow Builder
Types of flow builders
There are 4 types of flow builders:
- flowOf(): It is used to create flow from a given set of items.
- asFlow(): It is an extension function that helps to convert type into flows.
- flow{}: This is what we have used in the Hello World example of Flow.
- channelFlow{}: This builder creates flow with the elements using send provided by the builder itself.
Examples:
flowOf()
flowOf(4, 2, 5, 1, 7)
.collect {
Log.d(TAG, it.toString())
}
asFlow()
(1..5).asFlow()
.collect {
Log.d(TAG, it.toString())
}
flow{}
flow {
(0..10).forEach {
emit(it)
}
}
.collect {
Log.d(TAG, it.toString())
}
channelFlow{}
channelFlow {
(0..10).forEach {
send(it)
}
}
.collect {
Log.d(TAG, it.toString())
}
Now, we will learn how to create our Flow using the Flow builder. We can create our Flow for any task using the Flow Builder.
Creating Flow Using Flow Builder
Let's learn it through examples.
Move File from one location to another location
Here, we will create our Flow using the Flow Builder for moving the file from one location to another in the background thread and send the completion status on Main Thread.
val moveFileflow = flow {
// move file on background thread
FileUtils.move(source, destination)
emit("Done")
}
.flowOn(Dispatcher.Default)
CoroutineScope(Dispatchers.Main).launch {
moveFileflow.collect {
// when it is done
}
}
Downloading an Image
Here, we will create our Flow using the Flow Builder for downloading the Image which will download the Image in the background thread and keep sending the progress to the collector on the Main thread.
val downloadImageflow = flow {
// our image downloading code
// start downloading
// send progress
emit(10)
// downloading...
// ......
// ......
// send progress
emit(75)
// downloading...
// ......
// ......
// send progress
emit(100)
}
.flowOn(Dispatcher.Default)
CoroutineScope(Dispatchers.Main).launch {
downloadImageflow.collect {
// we will get the progress here
}
}
This is how we can create our Flow.
That's it for now.
Also, Let’s become friends on Twitter, Linkedin, Github, Quora, and Facebook.