Veeresh Charantimath Veeresh Charantimath - 28 days ago 10
Android Question

Using flatMapIterable() in RxJava2

I'm just starting out with RxJava and trying a sample project.

What I'm trying to achieve is

-> Get an object ->
which contains a list of sub-objects -> Check if the sub-list satisfies a predicate condition -> and emit the sub-objects if satisfies

This is my POJO

public class UpComingMovies {

@SerializedName("results")
private List<Movies> results;
}

public class Movies {

@SerializedName("overview")
private String overview;

@SerializedName("original_language")
private String originalLanguage;
}


So, from what I understand is that I can use
flatMapIterable
and transform the item to multiple observables and then use
filter
saying give me movies which has
originalLanguage.equals("en")


This is what I have tried to do

@GET("movie/upcoming")
Observable<UpComingMovies> getUpComingMovies(@Query("api_key") String apiKey, @Query("page") String page);

private final CompositeDisposable disposables = new CompositeDisposable();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

disposables.add(RetrofitConnection.getService()
.getUpComingMovies(Config.API_KEY, "1")
.flatMapIterable(new Function<UpComingMovies, Iterable<Movies>>() {
@Override
public Iterable<Movies> apply(@NonNull UpComingMovies upComingMovies) throws Exception {
// no instance(s) of the type variable(s) U exist so that the Observable<U> conforms to a disposable
return upComingMovies.getResults();
}
})
.filter(movies -> movies.getVoteCount() > 200).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableObserver<Movies>() {
@Override
public void onNext(@NonNull Movies movies) {

}

@Override
public void onError(@NonNull Throwable e) {

}

@Override
public void onComplete() {

}
}));
}


However, it does not compile.
Cleary I do not know how to do this, any help is appreciated

Jon Jon
Answer Source

The reason it doesn't compile is because you're returning an observable and your function signature is expecting an iterable:

new Function<UpComingMovies, Iterable<Movies>>() {
    @Override
    public Iterable<Movies> apply(@NonNull UpComingMovies upComingMovies) throws Exception {
        // List<Movies> is iterable
        return upComingMovies.getResults();

    }
}

If you fix it this way, then you can do

...flatMapIterable(...)
    .filter(new Predicate<Movies>() {
        @Override
        public boolean test(Movies movies) throws Exception {
                return movies.originalLanguage.equals("en");
        }
    })...