stcojo
stcojo

Reputation: 65

Rxjava filter observable of type List<Object>

I have a custom object called Post. A POST has a body and a title, both Strings.

I have a Retrofit instance which returns an Observable<List<Post>>

How can I use .filter on the Observable in order to filter based on individual Post objects, which have a title that starts with "t" ?

This is what I have so far, but can't wrap my head around it.

fetchData()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter(new Predicate<List<Post>>() {
                @Override
                public boolean test(List<Post> posts) throws Exception {

                    for (Post p : posts){
                        if (p.getTitle().startsWith("t"))

                            return true;
                    }
                    return false;
                }
            })
            .subscribe(getPostObserver());

Upvotes: 0

Views: 415

Answers (1)

homerman
homerman

Reputation: 3569

what you want to do is first decompose the emission of List<Post> into separate emissions for each Post. you can do that by flatMap()'ing the list, like so:

Observable.just(Arrays.asList(
    new Post("post #1", "this is the first post!"),
    new Post("post #2", "this is the second post!"),
    new Post("post #3", "this is the third post!")
))
    .flatMap(list -> {
      // turn the single emission of a list of Posts into a stream of 
      // many emissions of Posts...
      return Observable.fromIterable(list);
    })
    .filter(post -> {
      // apply filtering logic...
      return true;
    })
    .subscribe(...);

hope that helps!

Upvotes: 1

Related Questions