Concurrency with Kotlin Flow

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

Lesson 03: Leverage Flow Operators

Transforming 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 use what you learned in the previous lesson. Start Android Studio, and open the 03-leverage-flow-operators/Starter folder. Make sure you don’t continue on the project from the last lesson because the starter project has some new code for this lesson.

private val _categories: MutableStateFlow<List<MovieCategoryViewState>> = MutableStateFlow(emptyList())
val categories: Flow<List<MovieCategoryViewState>> = _categories

private val _moviesByCategories: MutableStateFlow<Map<String, List<MovieViewState>>> = MutableStateFlow(emptyMap())
val moviesByCategories: Flow<Map<String, List<MovieViewState>>> = _moviesByCategories
private fun fetchFavoriteCategories() {
  viewModelScope.launch {
    movieRepository.fetchFavoriteCategories()
      .map { favoriteCategories -> 
        favoriteCategories.map { MovieCategoryViewState(it.id, it.name) }
      }
      .collect { _categories.emit(it) }
  }
}
private fun fetchMoviesByCategories() {
  viewModelScope.launch {
    movieRepository.fetchMoviesByCategory()
      .transform { moviesByCategories ->
        val movieViewStates: Map<String, List<MovieViewState>> = moviesByCategories.mapValues { (category, movies) ->
          movies.map { movie ->
            val description = movieRepository.fetchMovieDescriptionsSuspending(movieId = movie.id)
            val imageRes = movieRepository.fetchMovieImage(movieId = movie.id)
            MovieViewState(
              id = movie.id,
              title = movie.title,
              description = description,
              imageRes = imageRes
            )
          } 
        }
        emit(movieViewStates)
      }
      .collect {
        _moviesByCategories.emit(it)
      }
  }
}
fun fetchMovieDescriptionsSuspending(movieId: String): String {
  return movieDatabase.getMovieDescription(movieId = movieId)
}
RootContainer(
  categories = categories,                    // here
  moviesByCategories = moviesByCategories,    // here
  onRatingsClicked = onRatingsClicked,
  onCategoryClicked = onCategoryClicked,
  onMovieClicked = onMovieClicked
)
See forum comments
Cinema mode Download course materials from Github
Previous: Transforming Operators Next: Filtering Operators