Using map on Kotlin's Stateflow

Viewed 4708

With LiveData inside a Viewmodel we use switchMap or Transformations.map like this

val recipesList = cuisineType.switchMap { repository.getDisplayRecipes(it.cuisineType).asLiveData() }

What would be the best way to do this with StateFlow? I know we can just use map like below, however this this would return me Flow<Flow<List< Recipe>>> which doesn't seem correct

val recipeListFlow = cuisineTypeStateFlow.map {
    repository.getDisplayRecipes(it.cuisineType)
}
1 Answers

Should be

val recipeListFlow = cuisineTypeStateFlow.flatMapLatest {
    repository.getDisplayRecipes(it.cuisineType)
}
Related