...

/

Different Ways of Building Flows

Different Ways of Building Flows

Learn about options for starting a flow.

Each flow needs to start somewhere. There are many ways to do this, depending on what we need. In this chapter, we’ll focus on the essential options.

Flow raw values

The simplest way to create a flow is by using the flowOf function, where we define what values this flow should have (similar to the listOf function for a list).

package kotlinx.coroutines.app
import kotlinx.coroutines.flow.*

suspend fun main() {
    flowOf(1, 2, 3, 4, 5)
        .collect { print(it) }
}
Creating a flow using flowOf function

At times, we might also need a flow with no values. For this, we have the emptyFlow() function (similar to the emptyList function for a list).

package kotlinx.coroutines.app
import kotlinx.coroutines.flow.*

suspend fun main() {
   emptyFlow<Int>()
       .collect { print(it) } // (nothing)
}
Using emptyFlow function when we need a flow with no values

Converters

We can also convert every Iterable, Iterator, or Sequence into a Flow ...