Concurrency with Kotlin Flow

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

Lesson 04: Advanced Flow Management

Flow Error Handling 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 short demo, you’ll see how to handle errors in flows.

@OptIn(ExperimentalCoroutinesApi::class)
private fun moviesForCategory(categoryId: String): Flow<List<MovieViewState>> =
  movieRepository.categories()
    .filter { it.id == categoryId }
    .flatMapLatest { movieCategory -> movieRepository.fetchMoviesForCategory(movieCategory.name) }
    .map { movies ->
      movies.map { movie ->
        val imageRes = movieRepository.fetchMovieImage(movieId = movie.id)
        MovieViewState(movie.id, movie.title, "", imageRes)
      }
    }
    .catch { throwable -> // HERE
      Log.e("CategoryViewModel", "Error happened", throwable)
      emit(emptyList())
    }
fun fetchMoviesForCategory(categoryName: String): Flow<List<Movie>> = flow {
  if (categoryName == "Action") { // HERE
    throw RuntimeException("Error fetching Action movies")
  }
  val movies = movieService.fetchMoviesForCategory(categoryName)
  emit(movies)
}
See forum comments
Cinema mode Download course materials from Github
Previous: Handling Errors in Kotlin Flow Next: Cancellations in Kotlin Flow