'Kotlin Flows map
I have an issue regarding kotlin flow merging. See below fun.
suspend fun method(filter: String): Flow<List<Model>> {
// Search.
val models: List<Model> = repo.getModels(filter) // suspend function
// Get favorites
val favoritesFlow: Flow<List<Int>> = otherRepo.getFavorites()
// Return models as Flow, but mark/unmark every model as favorite when favoritesFlow is updated.
??? val result = models + favoritesFlow ????
return result
}
I need to return a flow of list of models, but when the favorite flow is changed, I have to mark or unmark each model as favorite. Do you have any idea how could I do this?
Solution 1:[1]
You can combine emited values from both flows using Flow.combine()
fun favoriteModels() : Flow<List<Model>> = repo.getModels(filter)
.combine(otherRepo.getFavorites()) { models, favorites ->
models.filter { model -> favorites.contains(model.id) }
}
Solution 2:[2]
You can use map
or mapLatest
functions to transform favorites
into models
, something like this:
fun method(filter: String): Flow<List<Model>> = otherRepo.getFavorites().mapLatest { favorites ->
val models: List<Model> = repo.getModels(filter)
// do something with the models and favorites
models
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jakal |
Solution 2 | BigSt |