Kotlin Flows map

Viewed 4365

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?

2 Answers

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) }
    }

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
}
Related