Creating Flows with Flow builders
In this section, we will start by looking at creating Flows. To create a Flow, you can use a Flow builder.
The Kotlin Flow API has flow builders that you can use to create Flows. The following are the Kotlin Flow builders you can use:
flow {}
flowOf()
asFlow()
The flow
builder function creates a new Flow from a suspendable lambda block. Inside the block, you can send values using the emit
function. For example, this fetchMovieTitles
function of MovieViewModel
returns Flow<String>
:
class MovieViewModel : ViewModel() {
...
fun fetchMovieTitles(): Flow<String> = flow {
val movies = fetchMoviesFromNetwork()
movies.forEach { movie ->
emit(movie.title)
&...