Concurrency with Kotlin Flow

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

Lesson 04: Advanced Flow Management

Timeout Operator 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

This will be another short demo. You’ll see how to handle slow responses in flows using the timeout operator.

@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class) // HERE
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)
      }
    }
    .timeout(3000.milliseconds) // HERE   
    .catch { throwable ->                                         
      Log.e("CategoryViewModel", "Error happened", throwable)
      emit(emptyList())
    }
import kotlin.time.Duration.Companion.milliseconds
fun fetchMoviesForCategory(categoryName: String): Flow<List<Movie>> = flow {
  delay(5000) // Add a delay of 5 seconds
  val movies = movieService.fetchMoviesForCategory(categoryName)
  emit(movies)
}
See forum comments
Cinema mode Download course materials from Github
Previous: Cancellations in Kotlin Flow Next: Conclusion