Concurrency with Kotlin Flow

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

Lesson 02: Flow Fundamentals

Flow Builder 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 02-flow-fundamentals/Starter folder.

fun fetchMoviesByCategory(): Flow<Map<String, List<Movie>>> = flow {
  val moviesByCategory = movieService.fetchMoviesByCategory()
  emit(moviesByCategory)
}
import kotlinx.coroutines.flow.*
fun categories(): Flow<MovieCategory> = categoriesDummyData.asFlow()
fun fetchFavoriteCategories(): Flow<List<MovieCategory>> = flowOf(favoriteCategoriesDummyData)
fun movieRatings(): Flow<Pair<String, Float>> = callbackFlow {
  // 1
  val listener = object : MovieRatingListener {
    override fun onRatingUpdate(movieName: String, newRating: Float) {
      trySend(movieName to newRating)
    }
  }

  // 2
  movieRatingService.addRatingListener(listener)

  // 3
  awaitClose {
    movieRatingService.removeRatingListener(listener)
  }
}
private fun fetchMoviesByCategories() {
  viewModelScope.launch {
    movieRepository.fetchMoviesByCategory()
      .collect {
        _moviesByCategories.emit(it)
      }
  }
}

private fun fetchFavoriteCategories() {
  viewModelScope.launch {
    movieRepository.fetchFavoriteCategories()
      .collect { _categories.emit(it) } 
  }
}
See forum comments
Cinema mode Download course materials from Github
Previous: Kotlin Flow Builders Next: Conclusion