Concurrency with Kotlin Flow

Jun 5 2024 · Kotlin 1.9.20, Android 14, Android Studio Iguana

Lesson 03: Leverage Flow Operators

Combining Operators Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this demo, you’ll see how to use the combine and zip operators you covered in the previous lesson.

fun initCategory(categoryId: String) {
  viewModelScope.launch {
    combine(
      category(categoryId),
      moviesForCategory(categoryId),
    ) { category, movies -> CategoryScreenViewState(category, movies) }
      .collect { _screenViewState.emit(it) }
  }
}
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
init {
  fetchAllMoviesWithRatings()
}

private fun fetchAllMoviesWithRatings() {
  viewModelScope.launch {
    movieRepository.fetchMoviesByCategory()
      .map { moviesByCategories -> moviesByCategories.values.flatten() }
      .zip(movieRepository.fetchMovieRatings()) { movies, ratings ->
        movies.map { movie ->
          val rating = ratings[movie.id]!!
          MovieWithRatingViewState(movie.title, rating)
        }
          .sortedByDescending { it.rating }
      }
      .collect { _movies.emit(it) }
    }
  }
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.zip
import kotlinx.coroutines.flow.map
fun fetchMovieRatings(): Flow<Map<String, Int>> = flow {
  val movieRatings = movieService.fetchMovieRatings()
  emit(movieRatings)
}
See forum comments
Cinema mode Download course materials from Github
Previous: Combining Operators Next: Conclusion