Search code examples
androidkotlinmvvmretrofit2

Is there a way to do multiple filtering in Kotlin?


I am creating a podcast app for android. I want to filter list of podcast so I could get Health genre only.However there are about 3 different Health genres. I decided to filter all three of it. Now anytime I run the app,I get an empty list showing.However If I should filter only one health genre, everything works perfect.Here is my code.

suspend fun getHealthPodcast(): List {

    val requireGenreHF =Genre("1512", "Health & Fitness","https://itunes.apple.com/gb/genre/id1512")
    val requireGenreAH =Genre("1513", "Alternative Health","https://itunes.apple.com/gb/genre/id1513")
    val requireGenreMH =Genre("1517", "Mental Health","https://itunes.apple.com/gb/genre/id1517")

    val listGenre = listOf(requireGenreHF, requireGenreAH, requireGenreMH)

    val results = itunesRepo?.getHealthPodcast()

    if (results != null && results.isSuccessful) {

        val podcasts = results.body()?.feed?.results

        val filteredData = podcasts?.filter {
            it.genres.containsAll(listGenre)
        }
        if (filteredData != null) {
            return filteredData.map { podcast ->
                itunesPodcastView(podcast)
            }
        }
    }
    return emptyList()
}

Solution

  • containsAll() requires that genres contains all elements of listGenre, so podcast has to be marked as every health genre at the same time. If you wanted to search genres for any health one, you can do this:

    it.genres.any { it in listGenre }