Heads up... You’re accessing parts of this content for free, with some sections shown as
text.
Heads up... You’re accessing parts of this content for free, with some sections shown as
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)
}