简体   繁体   中英

How to filter one observable stream using another stream's element attribute as criteria using RxJava?

I'm working with two repositories with flatten data structure, ex. "MenuItemRepo" and "IngredientRepo". The relationship structure between them is: one MenuItem can contain many Ingredients, and a single Ingredient (ex. Cheese) can be part of many MenuItems. Database tables are modeled like below:

  • MenuItem Table Entry

    • string MenuItem-id
    • string name ...
  • MenuItem-Ingredient Reference Table Entry

    • string MenuItem-id
    • string Ingredient-id
  • Ingredient Table Entry

    • string Ingredient-id
    • bool isGlutenFree ...

Can I use RxJava to only select MenuItem elements from the [MenuItem stream] where their MenuItem ids that matches a particular Ingredient id in the [MenuItem-Ingredient reference stream]?

I use the .filter() operator to select element base on its own attribute, in one Flowable stream (ex. get all ingredients that are gluten free):

mIngredientsRepo.getItems()
                .flatMap(Flowable::fromIterable)
                .filter(ingredient-> ingredient.isGlutenFree)
                .toList() ....

This is to get a list of all glutenFree ingredients. But MenuItem stream in this case doesn't store the ingredient ids. Essentially I want to see if SQL-like JOIN filtering is possible, and if it would remain elegant with RxJava.

Currently I've implemented on the repository level with SQLite join statements. I would like to explore more intuitive and maintainable options in RxJava.

PS: This data structure is used for both local and remote, and is also used in Firebase, that's one of the reason why the structure is flat.

You can collect() those ingredient Ids into a HashSet , then in the menuitem stream, use filter() with contains check:

mIngredientsRepo.getItems()
.flatMapIterable(v -> v)
.collect(HashSet::new, (a, b) -> a.add(b.id))
.flatMapPublisher(set -> menuitems.filter(mi -> set.contains(mi.id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM