Search code examples
kotlinrx-javarx-kotlin

How to do the filter operator from a list of a list in rxjava


Good afternoon. So I got a list with a list inside like this:

    {
  "category" : [
    {
      "name": "Bathroom",
      "products": [
        {
          "name": "Sink01"
        },
        {
          "name": "Shower01"
        }
      ]
    },{
      "name": "Kitchen",
      "products": [
        {
          "name": "Table"
        },
        {
          "name": "Stove"
        }
      ]
    }
  ]
}

So if the user for example selects the category "Bathroom" I want to use rxjava to filter the list of products from the category "Bathroom" and if they select the category "Kitchen" I want to get the list of products from the category "Kitchen".

This is what I've tried so far:

    fun getProducts(category: Category): Single<MutableList<Product>> {
         return service.getProductsByCategories().filter{ response ->
             response.categoriesList.forEach {
                if (it.name == category.name) {
                  category.products
                }
             }
         }
    }

Right now I am getting "Typed mismatch. Requieres: Single<MutableList<Product>>, Found: Maybe<MyResponse!>!"

Why is this happening? What is the correct way to filter?

Thanks in advance.

Greetings


Solution

  • You can unroll the getProductsByCategories response, filter for the right category, map in the product list, then convert it to the desired output type:

    getProductsByCategories()
    .flattenAsObservable { it }
    .filter { it.name == category.name }
    .map { it.products }
    .single( ArrayList<Product>() )